创建validator/index.js
import Vue from 'vue'
import { ValidationProvider, ValidationObserver, extend, localize } from 'vee-validate'
import * as rules from 'vee-validate/dist/rules'
import zh_CN from 'vee-validate/dist/locale/zh_CN.json'
Object.keys(rules).forEach(rule => {
extend(rule, {
...rules[rule],
message: zh_CN[rule]
})
})
localize('zh_CN', zh_CN)
Vue.component('ValidationObserver', ValidationObserver)
Vue.component('ValidationProvider', ValidationProvider)
并在项目的main.js中 引入:import ‘@/validator’,即可全局使用该组件
<template>
<validation-provider v-if="flagIf" v-show="flagShow" :name="title" :style="isRequired ? 'color: #FF5257' : ''" :rules="Object.assign({required: required}, custRules)" v-slot="{ errors, validate }">
<md-field-item :disabled="disabled" :solid="solid" :title="isRequired ? '* ' + title : title" v-model="content" :content="content" :arrow="arrow" :placeholder="placeholder" @click="onClick">
</md-field-item>
<div class="errorMsg" v-show="errors.length > 0">{{errors[0]}}</div>
</validation-provider>
</template>
在自定义组件中使用,如上代码,其中custRules是根据自身需求写的计算属性,在调用该组件时由父组件传入的rules计算来。
computed: {
custRules() {
if (this.rules && this.rules[this.name]) {
return this.rules[this.name]
}
return {}
},
isRequired() {
if (this.required) {
return true
}
if (this.rules && this.rules[this.name] && this.rules[this.name]['required']) {
return true
}
return false
}
},
如果需要自定义验证规则,那么可以在validator/index.js或需要用到的页面上增加extend(都是全局的,所有页面可用),即可在rule中使用
如下:
import { extend } from 'vee-validate'
extend('minmax', {
validate(value, { min, max }) {
return value.length >= min && value.length <= max
},
params: ['min', 'max'],
message: '{_field_} 的长度应该在 {min} 在 {max} 之间'
})
//以下是data中的数据
{
rules: {
CarCode: {
min: 1,
max: 10
},
ClientMobile: {
digits: 11
},
ClientName: {
minmax: [3, 6]
}
}
}