The first step: encapsulation
class Check {
constructor() {
this.check = [];
/****
* 内置常用的校验规则
* @type {{minLength(*=, *, *): (*|undefined), isPhone(*=, *): (*|undefined), isEmpty(*, *): (*|undefined)}}
*/
this.state = {
isEmpty(val, msg) {
if (val === '') {
return msg;
}
},
minLength(val, length, msg) {
if (val && val.length < length) {
return msg;
}
},
isPhone(val, msg) {
if (!/(^1\d{10}$)/.test(val)) {
return msg
}
}
};
}
/*****
* 提供外部动态添加规则
* @param name
* @param rule
*/
addRule(name, rule) {
this.state[name] = rule
}
/****
* 将添加的规则保存在数组中
* @param value
* @param rules
*/
add(value, rules) {
rules.map(item => {
let strategyArr = item.strategy.split(":");
let errorMsg = item.errorMsg;
this.check.push(() => {
let strategy = strategyArr.shift();
strategyArr.unshift(value);
strategyArr.push(errorMsg);
return this.state[strategy] && this.state[strategy].apply(null, strategyArr);
})
});
}
/****
* 将校验结果遍历输出
* @returns {*}
*/
start() {
for (let i = 0; i < this.check.length; i++) {
let msg = this.check[i]();
if (msg) {
return msg;
}
}
}
}
export default Check
Step 2: Use
confirm() {
//实例化校验的类
let valdator = new Check();
//动态添加规则
valdator.addRule('maxLength',function (val,length,msg) {
if (val && val.length < length) {
return msg;
}
});
//给每个值添加规则
valdator.add(this.form.username, [
{
strategy: 'isEmpty',
errorMsg: '用户名不能为空!'
},
{
strategy: 'minLength:6',
errorMsg:"用户名不能少于6位"
}
]);
valdator.add(this.form.phone, [
{
strategy:"isPhone",
errorMsg: "请输入合法的手机号码"
}
]);
valdator.add(this.form.password, [
{
strategy: 'isEmpty',
errorMsg: '密码不能为空!'
},
{
strategy: 'minLength:6',
errorMsg:"密码不能少于6位"
},
{
strategy: 'maxLength:8',
errorMsg:"密码不能大于8位"
}
]);
//执行
let msg = valdator.start();
//有错误信息则提示
if (msg) {
console.log(msg)
return false;
}
}