用策略模式重构表单校验
//封装校验逻辑 var strategies = { isNotEmpty:function(value,errorMsg){ if(value ===''){ return errorMsg; } }, minLength:function(value,length,errorMsg){ if(value.length<length){ return errorMsg; } }, isMobile:function(value,errorMsg){ if(!/(!1[3|5|8][0-9]{9}&)/.test(value)){ return errorMsg; } } }
//准备实现validator类 var validataFunc = function(){ var valudator = new Validator();//创建一个validator对象 /*****添加检验规则*****/ validator.add(registerForm.userName,'isNotEmpty','用户名不能为空'); validator.add(registerForm.password,'minLength:6','密码长度不能少于6位'); validator.add(registerForm.phoneNumber,'isMobile','手机号码格式不正确'); var errorMsg = validator.start(); //获得校验结果 return errorMsg; } var registerForm = document.getElementById('registerForm'); registerForm.onsubmit = function(){ var errorMsg = validataFunc(); if(errorMsg){ alert(errorMsg); return false; } } //最后 实现Validator 类 var Validator = function(){ this.cache = []; //保存校验规则 } Validator.prototype.add = function(dom,rule,errorMsg){ var ary = rule.split(':'); //将strategy 和参数分开 this.cache.push(function(){ var strategy = ary.shift();//用户挑选的strategy ary.unshift(dom.value);//将input的value 添加到参数列表 ary.push(errorMsg); //将errorMsg 添加到参数列表 return strategies[strategy].apply(dom,ary); }) } Validator.prototype.start = function(){ for(var i=0,validatorFunc;validatorFunc = this.cache[i++];){ var msg = validatorFunc(); //开始校验 if(msg){ //如果有确切的返回值,则校验未通过 return msg; } } }