vue校验神器vee-validate

为什么推荐vee-validate

项目中经常会用到校验表单。通常UI库都自带有表单校验的功能。但有时候面对一些特殊就需要我们另辟蹊径。这款神器就是vee-validate

安装

bash
yarn add vee-validate@3 or npm install vee-validate@3 --save

用法

js
// main.js // 这里需要说明下ValidationObserver 常用于包装form表单 import { ValidationProvider, ValidationObserver } from 'vee-validate' // 自定义校验配置文件 import './utils/validate' // 全局注册注册 Vue.component('ValidationProvider', ValidationProvider) Vue.component('ValidationObserver', ValidationObserver)

组件中如何使用

vue
<validation-observer ref="form"> <form> <validation-provider rules="name" v-slot="{ errors }"> <div class="form-question"> <span class="label-span">姓名</span> <van-field placeholder="请输入" clearable v-model.trim="name"/> </div> <div class="error-tip" v-if="errors[0]"> {{ errors[0] }} </div> </validation-provider> <validation-provider rules="identityNumber" v-slot="{ errors }"> <div class="form-question"> <span class="label-span">身份证号</span> <van-field placeholder="请输入" clearable v-model.trim="identityNumber"/> </div> <div class="error-tip " v-if="errors[0]"> {{ errors[0] }} </div> </validation-provider> </form> </validation-observer>

自定义校验配置

js
import { extend, configure } from 'vee-validate'; import { required } from 'vee-validate/dist/rules'; import IdentityCodeValid from '@/utils/cardValidate'; import * as idCard from 'idcard'; configure({ classes: { invalid: 'is-invalid', failed: 'is-failed' } }); extend('identityNumber', { ...required, validate: (value) => { if (value) { const flag = idCard.verify(value) if (flag) { return true } else { return '请输入正确的身份证号码' } } else { return '请输入您的身份证号码' } } })

呈现效果

20221217220611b.png