<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="author" content="liuyi -liuyi.com" /> <meta name="copyright" content="liuyi - liuyi.com" /> <title>liuyi - www.liuyi.com</title> <style> input{border:1px solid #ccc;} input.ok{border:1px solid green;} input.error{border:1px solid red;} </style> <script> //方便维护 var json = { username:/^[a-z_]\w{5,31}$/i, pass:/^.{6,32}$/i, email:/^\[email protected][a-z0-9\-]+(\.[a-z]{2,8}){1,2}$/i, tel:/^(0\d{2,3}-)?[1-9]\d{6,7}$/, age:/^(1[89]|[2-9]\d|100)$/ }; window.onload = function(){ var oFrom = document.getElementById("from1"); var aInput = oFrom.getElementsByTagName("input"); //失焦校验 for(var i = 0; i < aInput.length; i++){ var re = json[aInput[i].name]; if(re){ (function(re){ aInput[i].onblur = function(){ //alert(re) checkText(re,this); }; })(re); } } function checkText(re,oText){ if(re.test(oText.value)){ oText.className = "ok"; return true; } else { oText.className = "error"; return false; } } oFrom.onsubmit = function(){ var bOk = true; for(var i = 0; i < aInput.length; i++){ var re = json[aInput[i].name]; if(re){ //做校验 /*if(re.test(aInput[i].value)){ aInput[i].className = "ok"; } else { aInput[i].className = "error"; bOk = false; //return false; }*/ if(checkText(re,aInput[i]) == false){ bOk = false; } } } return bOk; }; }; </script> </head> <body> <form id="from1" action="http://www.liuyi.com/"> 用户名:<input type="text" name="username" value="znstest"/><br /><br /> 密 码:<input type="text" name="pass" value=""/><br /><br /> 邮 箱:<input type="text" name="email" value="[email protected]"/><br /><br /> 座 机:<input type="text" name="tel" value="0214-31661688"/><br /><br /> 年 龄:<input type="text" name="age" value=""/><br /><br /> <input type="submit" /><br /><br /> </form> </body> </html>
时间: 2024-10-06 04:06:46