有关策略模式的简单介绍可以查看这篇文章:介绍
// 校验策略
const validateStrategies = {
isMobile(value, errMsg) {
if ( !/^1([38]\d|5[0-35-9]|7[3678]|99|4[579])\d{8}$/.test(value) ) {
return errMsg
}
},
isNonEmpty(value, errMsg) {
if (value === '') {
return errMsg
}
},
minLength(value, length, errMsg) {
if (value.length < Number(length)) {
return errMsg
}
}
}
// 校验类
function Validator() {
this.cache = []
}
Validator.prototype.add = function (dom, rules) {
for (let i = 0, rule; rule = rules[i++];) {
this.cache.push(function () {
const {
strategy,
errMsg // 校验失败弹出的错误信息
} = rule
const args = strategy.split(':') // 将多个参数用:分开,第一个参数是策略类型
const strategyType = args[0]
return validateStrategies[strategyType].apply(dom, [
dom.value,
...args.slice(1),
errMsg
])
})
}
}
Validator.prototype.validateForm = function () {
for (let i = 0, validatorFunc; validatorFunc = this.cache[i++];) {
// 校验时,遍历执行cache列表里的函数
const errMsg = validatorFunc()
if (errMsg) {
return errMsg
}
}
}
const userNameDom = {
value: 'syl'
}
const phoneDom = {
value: 15234083560
}
function validateFunc() {
const validator = new Validator()
validator.add(userNameDom, [
{
strategy: 'isNonEmpty',
errMsg: '用户名不能为空!'
},
{
strategy: 'minLength:6',
errMsg: '用户名不能少于6个字符'
}
])
validator.add(phoneDom, [
{
strategy: 'isMobile',
errMsg: '手机号码格式错误!'
}
])
const errMsg = validator.validateForm()
if (errMsg) {
alert(errMsg)
}
}
validateFunc() // 验证表单