标签:方便 exclude ace code def 号码 hub install blank
gitHub 地址:https://github.com/baianat/vee-validate
官网API 地址:https://baianat.github.io/vee-validate/api/
配置
先下载到项目 npm install vee-validate --save
封装一个自定义指令,方便后面使用
import {Validator, install as VeeValidate} from ‘vee-validate‘; import {required, min, max, excluded, included} from ‘vee-validate/dist/rules.esm.js‘; import {messages, rules} from ‘@/util‘; import ‘@/assets/style/validation.sass‘; export default function install(Vue) { Validator.extend(‘required‘, required); Validator.extend(‘min‘, min); Validator.extend(‘max‘, max); Validator.extend(‘excluded‘, excluded); Validator.extend(‘included‘, included); Vue.use(VeeValidate, { locale: ‘cn‘, dictionary: { cn: {messages} }, classes: [‘invalid‘], fieldsBagName: ‘xfields‘ }); for (let key in rules) { key && Validator.extend(key, rules[key]); } }
更多配置参考 https://baianat.github.io/vee-validate/configuration.html
util.js 下面放一些自定义的规则,列如
import {included} from ‘vee-validate/dist/rules.esm.js‘; export const messages = { required: field => `${field}为必填项`, max: (field, len) => `${field}长度不可多于${len}`, min: (field, len) => `${field}长度最多${len}` }; export const rules = { phone: { getMessage: () => ‘手机号码格式不正确‘, validate: value => /^(?=\d{11}$)^1(?:3\d|4[57]|5[^4\D]|66|7[^249\D]|8\d|9[89])\d{8}$/.test(value) }, email: { getMessage: field => `${field}格式不正确`, validate: email }, phoneExcluded: { getMessage: () => ‘手机号码格式不正确‘, validate: (value, args) => { return included(value, args) || /^(?=\d{11}$)^1(?:3\d|4[57]|5[^4\D]|66|7[^249\D]|8\d|9[89])\d{8}$/.test(value) // eslint-disable-line } }, }
在vue中使用方法,例如
<el-input v-model="form.successTextPrompt" v-validate="{required: true, max: 20}" data-vv-as="文字提示" data-vv-name="successTextPrompt" placeholder="请输入" /> <span class="error-msg" v-show="errors.has(‘successTextPrompt‘)">{{ errors.first(‘successTextPrompt‘) }}</span>
methods: {
submit() {
this.$validator.validateAll().then(valid => {
if (valid) {
// 校验成功
}
}
} }
标签:方便 exclude ace code def 号码 hub install blank
原文地址:https://www.cnblogs.com/shenjp/p/9534560.html