策略模式下表單驗證
class Validator {
constructor(strategies) {
this.cache = []
}
add(value, rules) {
if (!rules instanceof Array) throw 'rules should be Array'
var self = this
for(var i = 0, rule; rule = rules[i++];) {
(function(rule) {
var strategyArr = rule.strategy.split(':')
var errorMsg = rule.errorMsg
self.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
}
}
}
}
複製程式碼