const strategies = {
isCorrectPassword(value, errorMsg) {
if (!/^(?:(?=.*[A-Z])(?=.*[0-9])).\\S{7,19}$/.test(value)) {
return errorMsg;
}
return null;
},
isNotEmpty(value, errorMsg) {
if (value === '' || value === undefined) {
return errorMsg;
}
return null;
},
minLength(value, length, errorMsg) {
if (value.length < length) {
return errorMsg;
}
return null;
},
maxLength(value, length, errorMsg) {
if (value.length > length) {
return errorMsg;
}
return null;
},
isMobile(value, errorMsg) {
if (!/(^1[3|5|8][0-9]{9}$)/.test(value)) {
return errorMsg;
}
return null;
},
isNotAllEmpty(value = [], errorMsg) {
if (!value.some((i) => !!i)) {
return errorMsg;
}
return null;
},
};
class Validator {
constructor() {
this.cache = [];
}
add(value, rules) {
for (let i = 0, rule; (rule = rules[i++]); ) {
const strategyArray = rule.strategy.split(':') || [];
const { errorMsg } = rule;
this.cache.push(() => {
const strategy = strategyArray.shift();
strategyArray.unshift(value);
strategyArray.push(errorMsg);
return strategies[strategy].apply(value, strategyArray);
});
}
}
run() {
for (let i = 0, validatorFunc; (validatorFunc = this.cache[i++]); ) {
const msg = validatorFunc();
if (msg) {
return msg;
}
}
return null;
}
}
// 使用
const validator = new Validator();
validator.add(registerForm.userName, [
{
strategy: 'isNonEmpty',
errorMsg: 'userName not empty!',
},
{
strategy: 'minLength:6',
errorMsg: 'userName length should more than 6',
},
]);
validator.add(registerForm.password, [
{
strategy: 'minLength:6',
errorMsg: 'password length should more than 6',
},
]);
const errorMsg = validator.start();
if (errorMsg) {
console.log(errorMsg);
return errorMsg;
}