JavaScript簡單驗證表單空值及郵箱格式的方法
本文實例講述了JavaScript簡單驗證表單空值及郵箱格式的方法。分享給大家供大家參考,具體如下:
運行效果圖如下:

具體代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>Javascript 表單驗證</title>
<body>
<h3>(一)驗證必填項是否有空值。</h3>
<form action = "submitpage.html" onsubmit = "return validate_form(this)" method = "post">
Name:<input type = "text" name = "name" size = "20">
<input type = "submit" value = "Submit">
</form>
<h3>(二)驗證Email格式是否正確。</h3>
<form action = "submitpage.html" onsubmit = "return is_email_form(this)" method = "post">
Email:<input type = "text" name = "email" size = "20">
<input type = "submit" value = "OK">
</form>
<script>
//判斷內(nèi)容是否為空
function validate_form(thisform){
with (thisform){
if (!validate_required(name,"Name must be filled out!")){
name.focus();
return false
}
}
}
function validate_required(field,alerttxt){
with (field){
if (value==null||value==""){
alert(alerttxt);
return false
}else {
return true
}
}
}
//判斷內(nèi)容是否符合email的格式
function is_email_form(thisform){
with(thisform){
if(!checkEmail(email,"Not a valid e-mail address!")){
email.focus();
return false;
}
}
}
function checkEmail(field, alertText){
with(field){
apos = value.indexOf("@");
dotPos = value.indexOf(".");
if(apos<1 || dotPos-apos<2){
alert(alertText);
return false;
}else{
return true;
}
}
}
</script>
</body>
</html>
更多關(guān)于JavaScript相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《JavaScript表單(form)操作技巧大全》、《JavaScript數(shù)據(jù)結(jié)構(gòu)與算法技巧總結(jié)》、《JavaScript遍歷算法與技巧總結(jié)》、《JavaScript中json操作技巧總結(jié)》、《JavaScript錯誤與調(diào)試技巧總結(jié)》及《JavaScript數(shù)學運算用法總結(jié)》
希望本文所述對大家JavaScript程序設(shè)計有所幫助。
相關(guān)文章
div+css+js模擬tab切換效果 事件綁定 IE,firefox兼容
div+css+js模擬tab,這個版本,理論上可以添加無限個tab,而且,你只要管內(nèi)容的添加行了,不需要改JS2009-12-12
ES6新特性之類(Class)和繼承(Extends)相關(guān)概念與用法分析
這篇文章主要介紹了ES6新特性之類(Class)和繼承(Extends)相關(guān)概念與用法,結(jié)合實例形式較為詳細的分析了ES6中類(Class)和繼承(Extends)的基本概念、語法、使用方法與注意事項,需要的朋友可以參考下2017-05-05
9個讓JavaScript調(diào)試更簡單的Console命令
這篇文章主要為大家詳細介紹了9個讓JavaScript調(diào)試更簡單的Console命令,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-11-11

