<html> <head> <meta charset="uft-8"> </head> <body> <form action="" id="registerForm" method="post"> 请输入用户名:<input type="text" name="userName"/> 请输入密码:<input type="text" name="passWord"/> 请输入手机号码:<input type="text" name="phoneNumber"/> <input type="submit" value="提交"/> </form> <script> /***************策略对象*************/ var strategies = { isNotEmpty:function(value,errorMsg){ if(value === ‘‘){ return errorMsg; } }, minLength:function(value,length,errorMsg){ if(value.length<length){ return errorMsg; } }, isMobile:function(){ if(!/(^1[3|5|8][0-9]{9}$)/.test(value)){ return errorMsg; } } } /***************validator类***************/ var Validator = function(){ this.cache = []; }; Validator.prototype.add = function(dom,rules){ var self = this; for(var i=0,rule;rule = rules[i++];){ (function(rule){ var strategyAry = rule.strategy.solit(‘:‘); var errorMsg = rule.errorMsg; self.cache.push(function(){ var strategy = strategyAry.shift(); strategyAry.unshift(dom.value); strategyAry.push(errorMsg); return strategies[strategy].apply(dom,strategyAry); }) })(rule); } } Validator.prototype.start = function(){ for(var i=0,validatorFunc;validatorFunc = this.cache[i++];){ var errorMsg = validatorFunc(); if(errorMsg){ return errorMsg; } } } /************客户调用代码***********/ var registerForm = document.getElementById(‘registerForm‘); var validatorFunc = function(){ var validator = new Validator(); validator.add(registerForm.userName,[{ strategy:‘isNotEmpty‘, errorMsg:‘用户名不能为空‘ },{strategy:‘minLength:10‘, errorMsg:‘用户名长度不能小于10位‘ }]); validator.add(registerForm.passWord,[{ strategy:‘minLength:6‘, errorMsg:‘用户密码不能小于6位‘ }]); validator.add(registerForm.phoneNumber,[{ strategy:‘isMobile‘, errorMsg:‘手机号码格式不正确‘ }]); var errorMsg = validator.start(); return errorMsg; } registerForm.onsubmit = function(){ var errorMsg = validatorFunc(); if(errorMsg){ alert(errorMsg); return false; } } </script> </body> </html>
end: 拿走不谢
时间: 2024-10-05 15:57:18