根据网上现有的资料改的vue适用的策略验证,若是还须要别的验证直接本身添加规则就好了 。 上代码
新建一个js文件vue
let strategys = { isNotEmpty: (value, errorMsg) => { if(value === ''){ return errorMsg; } }, minLength: (value, length, errorMsg) => { if(value.length < length){ return errorMsg; } }, mobileFormat: (value, errorMsg) => { if(!/(^1[3|5|8][0-9]{9}$)/.test(value)) { return errorMsg; } } } export var Validator = function () { this.cache = []; // 保存效验规则 }; Validator.prototype.add = function(dom,rule,errorMsg) { var str = rule.split(":"); this.cache.push(function(){ // str 返回的是 minLength:6 var strategy = str.shift(); str.unshift(dom); // value添加进参数列表 str.push(errorMsg); // 把errorMsg添加进参数列表 return strategys[strategy].apply(dom,str); }); }; Validator.prototype.start = function () { for (var i = 0, validatorFunc; validatorFunc = this.cache[i++]; ) { var msg = validatorFunc() // 开始效验 并取得效验后的返回信息 if(msg) { return msg } } };
将文件导入要使用的组件或者视图中app
import { Validator } from './validate.js'
而后在你须要的地方导入就搞定了dom
methods: { submit_click() { let errorMsg = this.validateFunc(); if (errorMsg) { alert(errorMsg); return false } }, validateFunc() { let that = this; let validator = new Validator(); validator.add(that.userName, 'isNotEmpty', '用户名不能为空'); validator.add(that.password, 'minLength:6', '密码长度不能小于6位'); validator.add(that.phoneNumber, 'mobileFormat', '手机号码格式不正确'); var errorMsg = validator.start(); // 得到效验结果 return errorMsg; // 返回效验结果 } }