表單驗(yàn)證用于發(fā)生在服務(wù)器,客戶端已經(jīng)輸入所有必要的數(shù)據(jù),然后按下提交按鈕之后。如果一些已被輸入的客戶端的數(shù)據(jù)的已在錯(cuò)誤形式或者被簡(jiǎn)單地丟失,則服務(wù)器將必須的所有數(shù)據(jù)發(fā)送回客戶端,并請(qǐng)求的形式以正確的信息重新提交。這是一個(gè)漫長(zhǎng)的過(guò)程,會(huì)增加服務(wù)器負(fù)擔(dān)。
JavaScript中,提供了一種方法將其發(fā)送到web服務(wù)器之前驗(yàn)證客戶端的計(jì)算機(jī)上的形式的數(shù)據(jù)。表單驗(yàn)證通常執(zhí)行兩種方式。
基本驗(yàn)證 - 首先,該表必須進(jìn)行檢查,以確保數(shù)據(jù)輸入的需要將其每一個(gè)表單字段。這將通過(guò)表格的每個(gè)字段只需要循環(huán),并檢查數(shù)據(jù)。
數(shù)據(jù)格式驗(yàn)證 - 其次,該被輸入的數(shù)據(jù)必須檢查正確格式和值。這將需要放置更多的邏輯來(lái)測(cè)試數(shù)據(jù)的正確性。
我們將舉一個(gè)例子來(lái)了解驗(yàn)證的過(guò)程。下面是簡(jiǎn)單的形式進(jìn)行:
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
<!--
// Form validation code will come here.
//-->
</script>
</head>
<body>
<form action="/cgi-bin/test.cgi" name="myForm"
onsubmit="return(validate());">
<table cellspacing="2" cellpadding="2" border="1">
<tr>
<td align="right">Name</td>
<td><input type="text" name="Name" /></td>
</tr>
<tr>
<td align="right">EMail</td>
<td><input type="text" name="EMail" /></td>
</tr>
<tr>
<td align="right">Zip Code</td>
<td><input type="text" name="Zip" /></td>
</tr>
<tr>
<td align="right">Country</td>
<td>
<select name="Country">
<option value="-1" selected>[choose yours]</option>
<option value="1">USA</option>
<option value="2">UK</option>
<option value="3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
首先,我們將展示如何做一個(gè)基本的表單驗(yàn)證。在上面的表格要求validate()函數(shù)來(lái)驗(yàn)證數(shù)據(jù)在onsubmit事件發(fā)生。以下是validate()函數(shù)的實(shí)現(xiàn):
<script type="text/javascript">
<!--
// Form validation code will come here.
function validate()
{
if( document.myForm.Name.value == "" )
{
alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" )
{
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
}
if( document.myForm.Zip.value == "" ||
isNaN( document.myForm.Zip.value ) ||
document.myForm.Zip.value.length != 5 )
{
alert( "Please provide a zip in the format #####." );
document.myForm.Zip.focus() ;
return false;
}
if( document.myForm.Country.value == "-1" )
{
alert( "Please provide your country!" );
return false;
}
return( true );
}
//-->
</script>
現(xiàn)在,我們將看到我們?nèi)绾螌⑵涮峤坏絎eb服務(wù)器之前,驗(yàn)證我們輸入的表單數(shù)據(jù)。
這個(gè)例子說(shuō)明了如何驗(yàn)證輸入的電子郵件地址,這意味著電子郵件地址必須至少包含一個(gè)@符號(hào)和一個(gè)點(diǎn)(.)。此外,@絕不能是電子郵件地址的第一個(gè)字符,最后點(diǎn)必須在@符號(hào)后面的一個(gè)字符:
<script type="text/javascript">
<!--
function validateEmail()
{
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email ID")
document.myForm.EMail.focus() ;
return false;
}
return( true );
}
//-->
</script>