Summary of submission and verification methods
Summary of submission and verification methods
1. Use submit button, combined with onsubmit event to implement (most commonly used)
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>php.cn</title> <script type="text/javascript"> function checkForm() { //判斷用戶名是否為空 if(document.form1.username.value=="") { window.alert("用戶名不能為空!"); return false; }else { window.alert("驗(yàn)證通過!"); return true; } } </script> </head> <body> <form name="form1" method="post" action="login.php" onsubmit="return checkForm()"> 用戶名:<input type="text" name="username" /> 密碼:<input type="password" name="userpwd" /> <input type="submit" value="提交表單" /> </form> </body> </html>
2. Submit button , combined with the onclick event, to achieve form verification and submission
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>php.cn</title> <script type="text/javascript"> function checkForm() { //判斷用戶名是否為空 if(document.form1.username.value=="") { window.alert("用戶名不能為空!"); }else { window.alert("驗(yàn)證通過!"); } } </script> </head> <body> <form name="form1" method="post" action="login.php"> 用戶名:<input type="text" name="username" /> 密碼:<input type="password" name="userpwd" /> <input type="submit" value="提交表單" onclick="checkForm()" /> </form> </body> </html>
3. button button ( Ordinary button), combined with the submit() method to implement form verification submission
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>php.cn</title> <script type="text/javascript"> function checkForm() { if(document.form1.username.value.length == 0) { //如果用戶名為空 window.alert("用戶名不能為空!"); }else if(document.form1.username.value.length<5 || document.form1.username.value.length>20) { //如果用戶名長度小于5或大于20 window.alert("用戶名只能介于5-20個(gè)字符!"); }else if(checkOtherChar(document.form1.username.value)) { //如果用戶名含有特殊符號(hào) window.alert("用戶名中含有特殊符號(hào)!"); }else { //如果驗(yàn)證通過,提交表單 window.alert("驗(yàn)證通過!"); //表單提交方法 document.form1.submit(); } } function checkOtherChar(str) { //定義一個(gè)特殊符號(hào)的數(shù)組 var arr = ["*","&","<",">","$","\","/"]; //循環(huán)比較:數(shù)組中的每一個(gè)字符,與用戶名每一個(gè)字符進(jìn)行比對(duì) for(var i=0;i<arr.length;i++) { for(var j=0;j<str.length;j++) { if(arr[i]==str.charAt(j)) { return true; } } } //如果沒找到 return false; } </script> </head> <body> <form name="form1" method="post" action="login.php"> 用戶名:<input type="text" name="username" /> 密碼:<input type="password" name="userpwd" /> <input type="button" value="提交按鈕" onclick="checkForm()" /> </form> </body> </html>