當用戶輸完了所有必要的數(shù)據(jù)并且點擊了提交按鈕,接著就會進行表單的有效性進行驗證,表單驗證通常發(fā)生在服務器端。如果用戶輸入的一些數(shù)據(jù)存在錯誤,或者沒有輸入數(shù)據(jù),服務器就必須返回給客戶端所有的數(shù)據(jù),并且要求用戶重新提交正確的數(shù)據(jù)。這個過程確實是處理比較費時,而且給服務器造成很大壓力。
JavaScript 提供了一種方式在客戶端提交數(shù)據(jù)到服務器之前驗證表單數(shù)據(jù)的有效性。通常利用兩個函數(shù)來驗證表單數(shù)據(jù)的有效性。
我們舉個例子來說明有效性驗證的過程。如下是個簡單的例子:
<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>
首先我們會展示如何進行基本的表單有效性驗證。上面的代碼中我們調(diào)用了 validate() 函數(shù)驗證數(shù)據(jù)有效性,當事件 onsubmit 發(fā)生的時候。下面是對 validate() 函數(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>
接下來我們將會演示在將數(shù)據(jù)提交到服務器端之前我們?nèi)绾悟炞C數(shù)據(jù)的有效性。
這個例子演示如何驗證用戶輸入的郵箱地址的有效性,因為輸入的郵箱格式中必須包含 @ 符號和一個點號(.)。并且,符號 @ 不能作為作為郵箱地址的第一個字符,在 @ 符號之后和點號之前至少要有一個字符:
<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>
更多建議: