Vue 表单校验 vee-validate
Posted shenjp
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Vue 表单校验 vee-validate相关的知识,希望对你有一定的参考价值。
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(?:3d|4[57]|5[^4D]|66|7[^249D]|8d|9[89])d{8}$/.test(value) }, email: { getMessage: field => `${field}格式不正确`, validate: email }, phoneExcluded: { getMessage: () => ‘手机号码格式不正确‘, validate: (value, args) => { return included(value, args) || /^(?=d{11}$)^1(?:3d|4[57]|5[^4D]|66|7[^249D]|8d|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) {
// 校验成功
}
}
} }
以上是关于Vue 表单校验 vee-validate的主要内容,如果未能解决你的问题,请参考以下文章