javascript 学习之form表单的校验
表单提交前会做些校验,这里用了一个简单些的方法放在了一起。
html文件:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>表单正则校验</title> 5 <style> 6 input {border:1px solid #CCC; outline:none;} 7 input.ok {border:1px solid green;} 8 input.error {border:1px solid red;} 9 </style> 10 <script type="text/javascript" src="checkForm.js"></script> 11 <script> 12 window.onload = function(){ 13 formCheck("form1",function(oText){ 14 if(oText.name=='repass'){ 15 var pass = document.getElementsByName('pass')[0]; 16 if(oText.value != pass.value){ 17 return false; 18 } 19 } 20 }); 21 } 22 </script> 23 </head> 24 <body> 25 <form id="form1"> 26 用户名:<input type="text" name="uname"><br> 27 密码:<input type="text" name="pass"><br> 28 确认密码:<input type="text" name="repass"> 29 </form> 30 </body> 31 </html>
js文件:
1 /** 2 * Created by Administrator on 14-4-23. 3 */ 4 var json = { 5 uname:/^([\u4e00-\u9fa5])+$/, 6 pass:/^.{6,}$/, 7 repass:/^.{6,}$/ 8 }; 9 function formCheck(id,fnCheck){ 10 var oForm = document.getElementById(id); 11 var aInput = oForm.getElementsByTagName('input'); 12 function checkInput(oText,re){ 13 if(!re.test(oText.value)){ 14 oText.className = 'error'; 15 return false; 16 }else{ 17 if(!fnCheck){ 18 oText.className = 'ok'; 19 return true; 20 }else{ 21 if(false == fnCheck(oText)){ 22 oText.className = 'error'; 23 return false; 24 }else{ 25 oText.className='ok'; 26 return true; 27 } 28 } 29 } 30 } 31 for(var i=0;i<aInput.length;i++){ 32 var re = json[aInput[i].name]; 33 if(re){ 34 (function(re){ 35 aInput[i].onblur = function(){ 36 checkInput(this,re); 37 } 38 })(re); 39 } 40 } 41 42 //表单提交 43 oForm.onsubmit = function(){ 44 var ok = true; 45 for(var i=0;i<aInput.lenght;i++){ 46 var re = json[aInput[i].name]; 47 if(re){ 48 if(false == checkInput(aInput[i],re)){ 49 ok = false; 50 } 51 } 52 } 53 if(ok == false){ 54 return false; 55 } 56 } 57 }
这样可以方便的添加校验。

浙公网安备 33010602011771号