JavaScript中文參考手冊
/ JavaScript 表單驗證
JavaScript 表單驗證
JavaScript 可用來在數(shù)據(jù)被送往服務器前對 HTML 表單中的這些輸入數(shù)據(jù)進行驗證。
表單數(shù)據(jù)經(jīng)常需要使用 JavaScript 來驗證其正確性:
驗證表單數(shù)據(jù)是否為空?
驗證輸入是否是一個正確的email地址?
驗證日期是否輸入正確?
驗證表單輸入內容是否為數(shù)字型?
必填(或必選)項目
下面的函數(shù)用來檢查用戶是否已填寫表單中的必填(或必選)項目。假如必填或必選項為空,那么警告框會彈出,并且函數(shù)的返回值為 false,否則函數(shù)的返回值則為 true(意味著數(shù)據(jù)沒有問題):
function validateForm() { var x=document.forms["myForm"]["fname"].value; if (x==null || x=="") { alert("姓必須填寫"); return false; } }
以上函數(shù)在 form 表單提交時被調用:
實例
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> </head> <head> <script> function validateForm(){ var x=document.forms["myForm"]["fname"].value; if (x==null || x==""){ alert("姓必須填寫"); return false; } } </script> </head> <body> <form name="myForm" action="demo-form.php" onsubmit="return validateForm()" method="post"> 姓: <input type="text" name="fname"> <input type="submit" value="提交"> </form> </body> </html>
運行實例 ?
點擊 "運行實例" 按鈕查看在線實例
E-mail 驗證
下面的函數(shù)檢查輸入的數(shù)據(jù)是否符合電子郵件地址的基本語法。
意思就是說,輸入的數(shù)據(jù)必須包含 @ 符號和點號(.)。同時,@ 不可以是郵件地址的首字符,并且 @ 之后需有至少一個點號:
function validateForm(){ var x=document.forms["myForm"]["email"].value; var atpos=x.indexOf("@"); var dotpos=x.lastIndexOf("."); if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length){ alert("不是一個有效的 e-mail 地址"); return false; } }
下面是連同 HTML 表單的完整代碼:
實例
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> </head> <head> <script> function validateForm(){ var x=document.forms["myForm"]["email"].value; var atpos=x.indexOf("@"); var dotpos=x.lastIndexOf("."); if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length){ alert("不是一個有效的 e-mail 地址"); return false; } } </script> </head> <body> <form name="myForm" action="demo-form.php" onsubmit="return validateForm();" method="post"> Email: <input type="text" name="email"> <input type="submit" value="提交"> </form> </body> </html>
運行實例 ?
點擊 "運行實例" 按鈕查看在線實例