使用vee-validate验证表单
程序员文章站
2022-03-08 19:28:39
...
安装依赖
npm install vee-[email protected]2.0.0-rc.25
新建 validator.js
import Vue from 'vue'
import VeeValidate, {Validator} from 'vee-validate';
import zh_CN from 'vee-validate/dist/locale/zh_CN';
Vue.use(VeeValidate)
Validator.locale='zh_CN'
Validator.localize('zh_CN',{
messages:zh_CN.messages
})
Validator.extend('mobile', {
getMessage:()=>'格式不正确', //验证错误的提示信息
validate: value => { //验证规则
return value.length == 11 && /^((13|14|15|17|18)[0-9]{1}\d{8})$/.test(value)
}
});
Validator.extend('required', {
getMessage(field){
return field+'不能为空'
},
validate(value){
if(value){
return true
}
return false
}
});
在组件使用
<template>
<div class="validator">
<input v-model="input_01" type="text" v-validate="'required|mobile'" data-vv-name="aa邮箱" />
<br />
<span v-show="errors.has('aa邮箱')" class="text-style">{{ errors.first('aa邮箱') }}</span>
<br />
<el-radio-group v-model="radio" v-validate="'required'" data-vv-name="选项01">
<el-radio :label="3">备选项</el-radio>
<el-radio :label="6">备选项</el-radio>
<el-radio :label="9">备选项</el-radio>
</el-radio-group>
<br />
<span v-show="errors.has('选项01')" class="text-style">选项不能为空</span>
<br />
<el-radio-group v-model="radio02" v-validate="'required'" data-vv-name="选项02">
<el-radio :label="3">备选项</el-radio>
<el-radio :label="6">备选项</el-radio>
<el-radio :label="9">备选项</el-radio>
</el-radio-group>
<br />
<span v-show="errors.has('选项02')" class="text-style">选项不能为空</span>
<br />
<button @click="submit">提交</button>
</div>
</template>
<script>
export default {
data() {
return {
input_01: '',
radio: '',
radio02: '',
};
},
methods: {
submit() {
this.$validator.validate().then(valid => {
console.log('has:', this.$validator.errors.has('aa邮箱'));
if (true === valid) {
console.log('验证通过');
} else {
console.log('验证失败');
console.log(this.$validator.errors.all()[0]);
console.log(this.$validator.errors.all());
}
});
}
}
};
</script>