var strategys = { isNotEmpty: function (value, errorMsg) { if (value === '') { return errorMsg } }, // 限制最小长度 minLength: function (value, length, errorMsg) { if (value.length < length) { return errorMsg } }, // 手机号码格式 mobileFormat: function (value, errorMsg) { if (!/(^1[3|5|8][0-9]{9}$)/.test(value)) { return errorMsg } } } var Validator = function () { this.cache = [] // 保存效验规则 } Validator.prototype.add = function (dom, rules) { var self = this let lent = rules.length for (var i = 0; i < lent; i++) { let rule = rules[i]; (function (rule) { var strategyAry = rule.strategy.split(':') var errorMsg = rule.errorMsg self.cache.push(function () { var strategy = strategyAry.shift() strategyAry.unshift(dom) strategyAry.push(errorMsg) return strategys[strategy].apply(dom, strategyAry) }) })(rule) } } Validator.prototype.start = function () { let lent = this.cache.length for (var i = 0; i < lent; i++) { let validatorFunc = this.cache[i] var msg = validatorFunc() // 开始效验 并取得效验后的返回信息 if (msg) { return msg } } } export default Validator
调用方式
// 检测表单 test () { let test = new Validator() let value = this.post test.add(value.name, [ {strategy: 'isNotEmpty', errorMsg: '用户名不能为空'}, {strategy: 'minLength:6', errorMsg: '用户名长度不能小于6位'} ]) test.add(value.password, [ {strategy: 'isNotEmpty', errorMsg: '用户名不能为空'}, {strategy: 'minLength:6', errorMsg: '用户名长度不能小于6位'} ]) test.add(value.tel, [ {strategy: 'mobileFormat', errorMsg: '不是手机'} ]) var errorMsg = test.start() // 获得效验结果 return errorMsg // 返回效验结果 }, // 提交数据 jsSet () { let errorMsg = this.test() if (errorMsg) { return false } }