JavaScript 正則表示式驗證登入例項
阿新 • • 發佈:2018-10-31
程式碼片段:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>qq登入模擬測試</title> </head> <body> <form name="form1" action="#" method="post"> <input type="text" placeholder="賬號" name="username" ><br><br> <input type="password" placeholder="密碼" name="password" id="pw"> <input type="button" name="" id="btn" value="點選顯示" /> <br><br> <input name="Submit" type="button" onClick="check()" value="登入"/> </form> </body> <!--賬號密碼驗證--> <script type="text/javascript"> function check(){ /*非空*/ if(form1.username.value==""){ alert("賬號不能為空"); form1.username.focus(); return false; } /*含非數字、首字母為0 /^[0-9]*$/*/ var number=/^(0|[1-9][0-9]*)$/; var objExp1=new RegExp(number); if(objExp1.test(form1.username.value)==false){ alert("賬號不能含非數字和首字元為0"); form1.username.focus(); return false; } /*賬號小於6位數*/ if(form1.username.value.length < 6){ alert("賬號位數過小,請輸入6-11位數字"); form1.username.focus(); return false; } /*賬號大於11位數*/ if(form1.username.value.length > 11){ alert("賬號位數過大,請輸入6-11位數字"); form1.username.focus(); return false; } /*密碼非空*/ if(form1.password.value==""){ alert("密碼不能為空"); form1.password.focus(); return false; } /*密碼含有非符號、字母、數字以外字*/ var illegal=/^[
[email protected]#$%^&*()_+`\-={}:";'<>?,.\/]*$/g; var objExp2=new RegExp(illegal); if(objExp2.test(form1.password.value)==false){ alert("密碼含有非法字元"); form1.password.focus(); return false; } /*密碼小於6位數*/ if(form1.password.value.length < 6){ alert("密碼位數過小,請輸入6-16位數字"); form1.password.focus(); return false; } /*密碼大於16位數*/ if(form1.password.value.length > 16){ alert("密碼位數過大,請輸入6-16位數字"); form1.password.focus(); return false; } form1.submit(); } </script> <!--回顯密碼--> <script type="text/javascript"> window.onload=function(){ var btn=document.getElementById("btn"); var password=document.getElementById("pw") btn.onmousedown=function(){ password.type="text" }; btn.onmouseup=btn.onmouseout=function(){ password.type="password" } } </script> </html>
結果顯示:
希望對你學習有幫助。