vee-validate
安装
npm install vee-validate --save
引用
import Vue from 'vue';
import VeeValidate from 'vee-validate';
VeeValidate.Validator.localize('zh_CN');//改变成zh_CN中文的语言环境,如果不改默认提示是英文
Vue.use(VeeValidate);
组件设置
import VeeValidate, { Validator } from 'vee-validate';
import messages from 'assets/js/zh_CN';
Validator.updateDictionary({
zh_CN: {
messages
}
});
const config = {
errorBagName: 'errors', // change if property conflicts.
delay: 0,
locale: 'zh_CN',
messages: null,
strict: true
};
Vue.use(VeeValidate,config);
基本演示
<input v-validate="'required|email'" name="email" type="text">
<!-- 错误展示 -->
<span>{{ errors.first('email') }}</span>
- v-validate 表单验证指令
- name 确保表单的正确验证,展示表单对应的验证规则
- v-validate 传递规则(rules),使用管道符分割
- required 该领域是必需的
- email 表明该字段必须为电子邮件
- errors.first 展示错误消息
- errors.first(‘fieldName’) 显示单个错误消息
- errors.collect(‘fieldName’) 显示多条错误消息
- errors.all() 显示所有错误消息
- errors.collect() 按字段名称分组
默认验证规则
- after{target} - 比target要大的一个合法日期,格式(DD/MM/YYYY)
- alpha - 只包含英文字符
- alpha_dash - 可以包含英文、数字、下划线、破折号
- alpha_num - 可以包含英文和数字
- before:{target} - 和after相反
- between:{min},{max} - 在min和max之间的数字
- confirmed:{target} - 必须和target一样
- date_between:{min,max} - 日期在min和max之间
- date_format:{format} - 合法的format格式化日期
- decimal:{decimals?} - 数字,而且是decimals进制
- digits:{length} - 长度为length的数字
- dimensions:{width},{height} - 符合宽高规定的图片
- email - 不解释
- ext:[extensions] - 后缀名
- image - 图片
- in:[list] - 包含在数组list内的值
- ip - ipv4地址
- max:{length} - 最大长度为length的字符
- mimes:[list] - 文件类型
- min - max相反
- mot_in - in相反
- numeric - 只允许数字
- regex:{pattern} - 值必须符合正则pattern
- required - 不解释
- size:{kb} - 文件大小不超过
- url:{domain?} - (指定域名的)url
参考链接:验证规则
自定义规则
创建规则
<!-- 功能表 -->
const validator = (value, args) => {
// Return a Boolean or a Promise that resolves to a boolean.
};//最基本的形式,只返回布尔值或者Promise,带默认的错误提示
<!-- 对象表 -->
const validator = {
getMessage(field, args) {// 添加到默认的英文错误消息里面
// will be added to default locale messages.
// Returns a message.
},
validate(value, args) {
// Returns a Boolean or a Promise that resolves to a boolean.
}
};
使用自定义规则
import { Validator } from 'vee-validate';
const isMobile = { //定义字典,设置验证出现错误结果时的显示字段
messages: {
en:(field, args) => field + '必须是11位手机号码',
},
validate: (value, args) => {
return value.length == 11 && /^((13|14|15|17|18)[0-9]{1}\d{8})$/.test(value)
}
}
Validator.extend('mobile', isMobile);
//或者直接
Validator.extend('mobile', {
messages: {
en:field => field + '必须是11位手机号码',
},
validate: value => {
return value.length == 11 && /^((13|14|15|17|18)[0-9]{1}\d{8})$/.test(value)
}
})
<!-- 使用 -->
<input v-validate data-rules="required|mobile" :class="{'input': true, 'is-danger': errors.has('mobile') }" name="mobile" type="text" placeholder="Mobile">
<span v-show="errors.has('mobile')" class="help is-danger">{{ errors.first('mobile') }}</span>
//如果需求里不需要多一个提示的标签,只需要在错误验证时显示警示颜色,那可以通过在input标签上写 :class="{error:error.has('idCard')}" 来实现。