JS简单的一些表单验证
效果图:
代码如下,复制即可用:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <style type="text/css"> input{ width:200px; height:25px; line-height:25px; font-size:16px; font-family:"微软雅黑"; color:#a2a2a2; outline:none; } input.red{border:1px solid red;} input.green{border:1px solid green;} span.false{ color:red; font-size:18px; font-family:"微软雅黑"; font-weight:bold; display:none; } span.true{ color:green; font-size:18px; font-family:"微软雅黑"; font-weight:bold; display:none; } </style> <title>简单表单验证</title> </head> <body> <p> <input type="text" name="user" placeholder ="请输入您要注册的账号" /> <span class="false">x您输入的账号不符合规范</span> <span class="true">输入正确</span> </p> <p> <input type="text" name="pwd" placeholder = "请输入您的密码" /> <span class="false">x您输入的密码不正确</span> <span class="true">输入正确</span> </p> <p> <input type="text" name="pwd2" placeholder ="请再次输入您的密码" /> <span class="false">x您两次输入的密码不一致</span> <span class="true">输入正确</span> </p> <p> <input type="text" name="QQ" placeholder="请输入您的QQ号码"/> <span class="false">x您输入的QQ号码不正确</span> <span class="true">输入正确</span> </p> <p> <input type="text" name="tel" placeholder="请输出您的手机号码" /> <span class="false">x您输入的手机号码不正确</span> <span class="true">输入正确</span> </p> <p> <input type="text" name="mail" placeholder="请输出您的邮箱号码" /> <span class="false">x您输入的邮箱号码不正确</span> <span class="true">输入正确</span> </p> <p> <input type="text" name="card" placeholder="请输入您的身份证号码"/> <span class="false">x您输入的身份证号码不正确</span> <span class="true">输入正确</span> </p> <script type="text/javascript"> var oInp = document.getElementsByTagName("input"); for (var i =0;i<oInp.length ;i++ ){ oInp[i].onfocus = function(){ if (this.name=="pwd2" && oInp[1].className!="green"){ alert("第一次输入错误"); oInp[1].focus(); return; } fn.call(this,this.name); }; oInp[i].onkeyup = function(){ fn.call(this,this.name); } }; function fn(key){ var val =this.value; var bool =key=="pwd2"?val==oInp[1].value:reg[key].test(val) ; if (bool) { this.className= "green"; this.parentNode.getElementsByClassName("false")[0].style.display = "none"; this.parentNode.getElementsByClassName("true")[0].style.display = "inline"; }else{ this.className = "red"; this.parentNode.getElementsByClassName("true")[0].style.display = "none"; this.parentNode.getElementsByClassName("false")[0].style.display = "inline"; } } //正则集合 var reg = { 'user' : /^[a-z_]/w{5,17}$/i, 'pwd' : /^[/w/`/!/@/#/$/%/^&/*/(/)/./,/+/-/</>///|///:/;/"/"/'/'/~/?/[/]/{/}]{6,18}$/, 'QQ' : /^[1-9]/d{4,9}$/, 'tel' : /^1[34578]/d{9}$/, 'mail' : /^/w+@[a-z0-9]{2,}(/.[a-z]{2,}){1,3}$/i, 'card' : /^[1-9]/d{16}[0-9xX]$/ }; </script> </body> <html>
如果你们有更好的一些表单验证,欢迎大家一起来分享,如有错误,请联系我改正,非常感谢!!!
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/12315.html