非空验证
1 <head> 2 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 3 <title>无标题文档</title> 4 </head> 5 6 <body> 7 <form action="好友列表选中.html" method="get"> 8 <input type="text" name="uid" id="uid" onblur="yanzheng()"/> 9 <span id="tishi"></span> 10 <br/> 11 <input type="submit" value="提交" onclick="return check()"/> 12 </form> 13 </body> 14 <script type="text/javascript"> 15 16 function yanzheng(){ 17 var a=document.getElementById("uid"); 18 var b=document.getElementById("tishi"); 19 if(a.value==""){ 20 b.innerText ="用户名不能为空!"; 21 b.style.color ="red"; 22 }else{ 23 b.innerText ="用户名可以使用"; 24 b.style.color ="green"; 25 } 26 } 27 28 </script> 29 </html>
相等验证
1 <body> 2 <form action="好友列表选中.html" method="get"> 3 4 <input type="text" name="pwd1" id="pwd1"/> 5 <br/> 6 <input type="text" name="pwd2" id="pwd2" onblur="xiangdeng()"/> 7 <input type="submit" value="提交" onclick="return check()"/> 8 </form> 9 </body> 10 <script type="text/javascript"> 11 12 function xiangdeng(){ 13 var p1=document.getElementById("pwd1"); 14 var p2=document.getElementById("pwd2"); 15 if(p1.value==p2.value){ 16 alert("密码可用"); 17 }else{ 18 alert("输入的密码不一致"); 19 } 20 } 21 22 </script> 23 </html>
范围验证
1 <body> 2 <form action="好友列表选中.html" method="get"> 3 <input type="text" name="age" id="age" onblur="nianling()"/> 4 <br/> 5 <input type="submit" value="提交" onclick="return check()"/> 6 </form> 7 </body> 8 <script type="text/javascript"> 9 10 function nianling(){ 11 var a=document.getElementById("age"); 12 if(parseInt(a.value)>=18 && parseInt(a.value)<=50){ 13 alert("OK"); 14 }else{ 15 alert("年龄超出"); 16 } 17 } 18 19 </script> 20 </html>
正则验证,关于正则表达式,可记住常用的几种。
1 <body> 2 <form action="好友列表选中.html" method="get"> 3 4 <input type="text" name="email" id="email" onblur="youxiang()"/> 5 <input type="submit" value="提交" onclick="return check()"/> 6 </form> 7 </body> 8 <script type="text/javascript"> 9 10 function youxiang(){ 11 var e=document.getElementById("email"); 12 if(e.value.match(/^w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*$/)==null){ 13 alert("格式不正确"); 14 }else{ 15 alert("邮箱正确"); 16 } 17 } 18 </script> 19 </html>
关于职业素养:不能相信用户的任何输入,必须经过控制或过滤。正视这一点,就能减少程序漏洞,保证程序安全和完整。