Vue-表单校验
1.新建xxx.js
定义策略对象和策略类
1 /*策略对象*/ 2 const strategies = { 3 // 是否为空 4 isNonEmpty(value, errorMsg) { 5 return value === '' ? errorMsg : void 0; 6 }, 7 // 最小长度 8 minLength(value, length, errorMsg) { 9 return value.length < length ? errorMsg : void 0; 10 }, 11 // 是否手机号 12 isMoblie(value, errorMsg) { 13 return !/^1(3|4|5|6|7|8|9)[0-9]{9}$/.test(value) ? errorMsg : void 0; 14 } 15 }; 16 // 策略类 17 class Validator { 18 constructor() { 19 this.cache = []; 20 } 21 add(iptVal, rules) { 22 for (const rule of rules) { 23 let strategyAry = rule.strategy.split(':'); 24 let errorMsg = rule.errorMsg; 25 this.cache.push(() => { 26 let strategy = strategyAry.shift(); 27 strategyAry.unshift(iptVal); 28 strategyAry.push(errorMsg); 29 return strategies[strategy].apply(iptVal, strategyAry); 30 }); 31 } 32 } 33 start() { 34 for (let validatorFunc of this.cache) { 35 let errorMsg = validatorFunc(); //开始校验 36 if (errorMsg) { 37 return errorMsg; 38 } 39 } 40 } 41 } 42 43 export default Validator;
2.在组件中引入
import Validator from './xxx.js';
3.使用
a.组件内定义表单验证方法
1 validatorFunc() { 2 let validator = new Validator(); 3 validator.add(this.reportData.phone, [ 4 { 5 strategy: 'isNonEmpty', 6 errorMsg: '手机号不能为空' 7 }, 8 { 9 strategy: 'isMoblie', 10 errorMsg: '号码格式错误' 11 } 12 ]); 13 validator.add(this.reportData.name, [ 14 { 15 strategy: 'isNonEmpty', 16 errorMsg: '未填写姓名' 17 } 18 ]); 19 validator.add(this.reportData.code, [ 20 { 21 strategy: 'isNonEmpty', 22 errorMsg: '未填写验证码' 23 } 24 ]); 25 let errorMsg = validator.start(); 26 return errorMsg; 27 },
b.在提交表单时调用此方法
1 const errorMsg = this.validatorFunc(); 2 if (errorMsg) { 3 this.$toast(errorMsg); 4 return; 5 } else { 6 this.$ajax(); 7 }