//定义一个策略 var msg={ default:"输入格式不正确!", maxLength:"输入长度太长!", minLength:"输入长度不够!", isEmpty:"输入的值不能为空!", isNumber:"输入的值必须是纯数字!", success:"正确!" } //写验证规则 var ruleList={ isNumber:function(value,info){ if(!/^\d+$/.test(value)){ return info||msg["isNumber"]; } else{ return msg["success"]; } }, default:function(value,info){ if(!/^\w+$/.test(value)){ return info||msg["default"]; } else{ return msg["success"]; } }, maxLength:function(value,len,info){ if(value.length>len){ return info||msg["maxLength"]; } else{ return msg["success"]; } }, minLength:function(value,len,info){ if(value.length<len){ return info||msg["minLength"]; } else{ return msg["success"]; } }, isEmpty:function(value,info){ if(value.length==0){ return info||msg["isEmpty"]; } else{ return msg["success"]; } }, replace:function(value){ return value.replace(/\s/g,''); } } //建立一个验证类 function Validator(){ this.item={};//存储验证规则 } Validator.prototype={ constructor:Validator, add:function(id,value,rule,info){ if(!this.item[id]){ this.item[id]=[]; } //去除value值的空格 value=ruleList.replace(value); var arr=[value]; //规则检测 var len; if(rule.indexOf(":")!=-1) { var split=rule.split(":"); arr.push(split[1]); rule=split[0]; } arr.push(info); this.item[id].push([ruleList[rule],arr]); console.log(this.item); }, start:function(id){ if(!this.item[id]){ return; } this.item[id].map(function(list){ console.log(list[0].apply(null, list[1])); }); } } var validator=new Validator(); validator.add("userid","abcdef_12345","maxLength:10","长度不能大于10位!"); validator.add("userid","","isEmpty"); validator.add("userpwd","1245","minLength:5","长度不能小于5位!"); validator.start("userid"); validator.start("userpwd");
策略模式实现表单验证
最新推荐文章于 2022-05-23 23:19:10 发布