策略模式下表单验证
class Validator {constructor(strategies) {this.cache = []}add(value, rules) {if (!rules instanceof Array) throw 'rules should be Array'var self = thisfor(var i = 0, rule; rule = rules[i++];) {(function(rule) {var strategyArr = rule.strategy.split(':')var errorMsg = rule.errorMsgself.cache.push(function() {var strategy = strategyArr.shift();strategyArr.unshift(value)strategyArr.push(errorMsg)return strategies[strategy].apply(null, strategyArr)})})(rule)}}start() {for (var i = 0, fn; fn = this.cache[i++]; ) {var errorMsg = fn()if (errorMsg) {return errorMsg}}}
}
复制代码