Javascript:表單驗(yàn)證(驗(yàn)證空值/郵箱格式)
來源:程序員人生 發(fā)布時間:2015-02-09 09:06:18 閱讀次數(shù):2755次
代碼整理自w3school:http://www.w3school.com.cn
效果圖:

示例代碼:
<!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⑻" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>Javascript 表單驗(yàn)證</title>
<body>
<h3>(1)驗(yàn)證必填項(xiàng)是不是有空值。</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>(2)驗(yàn)證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>
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈