// 定义策略var strategy = {
isNotEmpty: function(value, errorMsg){
if(value === ''){
return errorMsg;
}
},
minLength: function(value, length, errorMsg){
if(value.length < length){
return errorMsg;
}
},
mobileFormat: function(value, errorMsg){
if(!/(^1[3|5|8][0-9]{9}$)/.test(value)){
return errorMsg;
}
}
}function Validator() {
this.cache = [];
}
Validator.prototype.add = function(value, rules){
for(var i = 0, rule; rule = rules[i++];){
var self = this;
(function(rule){
self.cache.push(function(){
var strategyRule = rule.strategy.split(':');
var strategyName = strategyRule.shift(); // 各位看官注意啦, 如果直接使用[value].concat(strategyRule.push(rule.errorMsg))会出问题
// 什么问题呢?
// strategyRule.push(rule.errorMsg)这货会返回length, 我TM调试了半天!
strategyRule.push(rule.errorMsg);
var arr = [value].concat(strategyRule);
return strategy[strategyName].apply(null,arr);
})
})(rule);
}
}
Validator.prototype.check = function(){
for(var i = 0, checkFn; checkFn = this.cache[i++];){
var msg = checkFn();
if(msg){
return msg;
}
}
}var validator = new Validator();
validator.add('12345', [
{
strategy: 'isNotEmpty',
errorMsg: 'in not empty'
},
{
strategy: 'minLength:10',
errorMsg: 'length is less than 10'
}
]);var tip = validator.check(); // tip: length is less than 10以上就是验证策略模式实现的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号