?? ? ?? ?? ??
?? ? ?? ?? ??
1. onsubmit ???? ?? ?? ??? ?????(?? ????? ???)
<!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() { //判斷用戶(hù)名是否為空 if(document.form1.username.value=="") { window.alert("用戶(hù)名不能為空!"); return false; }else { window.alert("驗(yàn)證通過(guò)!"); return true; } } </script> </head> <body> <form name="form1" method="post" action="login.php" onsubmit="return checkForm()"> 用戶(hù)名:<input type="text" name="username" /> 密碼:<input type="password" name="userpwd" /> <input type="submit" value="提交表單" /> </form> </body> </html>
2 . ?? ?? ? ??? ???? ?? onclick ???? ??? ?? ??
<!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() { //判斷用戶(hù)名是否為空 if(document.form1.username.value=="") { window.alert("用戶(hù)名不能為空!"); }else { window.alert("驗(yàn)證通過(guò)!"); } } </script> </head> <body> <form name="form1" method="post" action="login.php"> 用戶(hù)名:<input type="text" name="username" /> 密碼:<input type="password" name="userpwd" /> <input type="submit" value="提交表單" onclick="checkForm()" /> </form> </body> </html>
3. ?? ?? ? ??? ???? ?? submit() ???? ??? ?? ?? ??
<!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) { //如果用戶(hù)名為空 window.alert("用戶(hù)名不能為空!"); }else if(document.form1.username.value.length<5 || document.form1.username.value.length>20) { //如果用戶(hù)名長(zhǎng)度小于5或大于20 window.alert("用戶(hù)名只能介于5-20個(gè)字符!"); }else if(checkOtherChar(document.form1.username.value)) { //如果用戶(hù)名含有特殊符號(hào) window.alert("用戶(hù)名中含有特殊符號(hào)!"); }else { //如果驗(yàn)證通過(guò),提交表單 window.alert("驗(yàn)證通過(guò)!"); //表單提交方法 document.form1.submit(); } } function checkOtherChar(str) { //定義一個(gè)特殊符號(hào)的數(shù)組 var arr = ["*","&","<",">","$","\","/"]; //循環(huán)比較:數(shù)組中的每一個(gè)字符,與用戶(hù)名每一個(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; } } } //如果沒(méi)找到 return false; } </script> </head> <body> <form name="form1" method="post" action="login.php"> 用戶(hù)名:<input type="text" name="username" /> 密碼:<input type="password" name="userpwd" /> <input type="button" value="提交按鈕" onclick="checkForm()" /> </form> </body> </html>