Vue 插件 vee-validate校验插件详解大全

1. vee-validate 简介

veeValidate 是专用于 Vue.js 的验证库。它有很多开箱即用的验证规则,也支持自定义验证规则。它基于模板,所以它和 HTML5 的验证 API 比较类似,而且我们

也比较熟悉。我们可以验证 HTML5 input 输入框,以及我们自定义的 Vue 组件。

特点:

  • 基于模板的验证
  • 提供了许多开箱即用的验证规则
  • 一流的本地化支持
  • 可以验证 HTML5 input 输入框和自定义 Vue 组件
  • 自定义规则和错误消息

2. 安装

npm install vee-validate --save

或者使用 CDN

<script src="https://unpkg.com/vee-validate"></script>

用npm 安装的时候要注意vue的版本和 vee-validate 版本的匹配,我们来栏官网的提示:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-impF8dD9-1650439580527)(D:\study\项目\前端\vue+elementui\VeeValidate.assets\image-20220420104436605.png)]

vue3–>安装 v4.x vue2–> 可以安装小于 v3.x。

npm install vee-validate@2--save

怎么查看vee-validate

npm view vee-validate versions --json

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XtM7GrEO-1650439580529)(D:\study\项目\前端\vue+elementui\VeeValidate.assets\image-20220420101549747.png)]

3. 引用

import Vue from 'vue';
import VeeValidate from 'vee-validate';
Vue.use(VeeValidate);

4.参数介绍

import Vue from 'vue';
import VeeValidate from 'vee-validate';
const config = {
    aria: true,
    classNames: {},
    classes: false,
    delay: 0,
    dictionary: null,
    errorBagName: 'errors', // change if property conflicts
    events: 'input|blur',
    fieldsBagName: 'fields',
    i18n: null, // vue-i18n 插件实例
    i18nRootKey: 'validations', // the nested key under which the validation messages will be located
    inject: true,
    locale: 'en',
    validity: false
};
Vue.use(VeeValidate, config);

参数介绍:

  • aria - boolean - true - 允许在 HTML inputs 输入框上设置 aria-invalid 和 aria-required 属性
  • classNames - object - 空 - 根据 input 输入框的状态应用的 class
  • classes - boolean - false - 对要验证的 HTML inputs 输入框应用自动类
  • delay - number - 0 - 所有 inputs 输入框默认的防抖时间(仅影响验证)
  • dictionary - object|null - null - 一个要与内部字典合并的字典
  • errorBagName - string - ‘errors’ - ErrorBag 对象的名称,会被注入到每个 Vue 实例的 data 里。用于避免与其他插件冲突。
  • events - string - ‘input’ - 将要被监听的、用来触发认证的、以 ‘|’ 分隔的默认事件名称列表。如果提供了空字符串,将禁用所有监听器。
  • fieldsBagName - string - ‘fields’ - 字段(标志)对象的名称,会被注入到每个 Vue 实例的 data 里。
  • fastExit - boolean - true - 对每个字段的验证,是否应在首次验证失败后停止,我们可以使用 continues 和 bails 修饰符,选择加入或退出任一设置
  • i18n - VueI18n|null - null - vue-i18n 实例,如果提供了,将使用 i18n 插件,集成到 vee-validate,并将使用该实例来生成错误消息,而不使用内置字典。
  • i18nRootKey - string - ‘validations’ - 每个语言环境的验证消息的 key 名
  • inject - boolean - true - 指定是否应为所有组件自动注入验证器实例
  • locale - string - ‘en’ - 验证消息的默认语言
  • validaty - boolean - false - 在本地 HTML inputs 输入框上,设置自定义有效性 Constraint Validation(约束验证)

delay 字段详解

我们可以指定一个延迟,对 input 事件进行去抖动,一个常见的场景是,我们可能希望等待用户停止键入,然后再验证字段,以限制验证触发频率。(不需要用户

每按下键盘一次,我们就触发验证,稍有个延迟)

我们可以全局配置,也可以在每个组件中设置(在要验证的字段上添加 data-vv-delay 属性来实现):

     <el-form-item prop="username">
          <el-input
            v-validate="'required|between:3,8'"
            data-vv-delay="1000"
            prefix-icon="el-icon-user"
            v-model="loginForm.username"
            placeholder="ID"
            name="username"
            autofocus/>
            <span v-show="errors.has('username')" class="error-style">*  {{ errors.first('username') }} </span>
        </el-form-item>

5.基本使用

在Vue中引用 vee-validate

怎么使用呢?

我们需要将 v-validate 指令添加到我们需要验证的 input 输入框上,一定要确保input输入框有一个name属性,用来生成错误信息。

v-validate 需要传入一个规则字符串,规则如下:

使用‘|’ 管道符分割的验证规则。例如

为了显示错误信息,我们简单的使用 errors.first 方法,来获取该字段的第一个错误。

<span> {{ errors.first('email')}} </span>

1.单个规则的设置

const single = ‘required’;

2.多个规则设置

constructormultiple = ‘required|numeric’

规则表达式,也可以是一个复杂的、可读性更好的规则对象:

const single = { required: true };
const multiple = {
    required: true,
    numeric: true,
    email: true,
};

规则参数:

1.逗号分隔的参数列表,适用于字符串格式

const rules = ‘included:1,2,3,4’;

2.一个 包含参数值的数组(适用于对象格式)

const ruleObj = {included:[1,2,3,4]}

内置校验规则:

规则含义
alpha只包含英文字符
alpha_dash可以包含英文、数字、下划线、破折号
alpha_num可以包含英文和数字
alpha_spaces可以包含英文和数字
between:{min},{max}在min和max之间的数字
confirmed:{target}必须和target一样
digits:{length}长度为length的数字
dimensions:{width},{height}符合宽高规定的图片
email符合邮箱规则
excluded排除,不包括
ext:[extensions]后缀名
image图片
integer整型
is必须是
is_not不是
length规定输入内容长度
max:{length}规定输入内容的最大长度为length
min:{length}规定输入内容的最小长度为length
max_value:{val}规定输入最大数值为val的
min_value:{val}规定输入最小数值为val的
mimes:[list]文件类型
numeric只允许数字
oneOf其中之一

上面只是展示一部分规则,详情请参考:

内置校验的JS 的路径: node_modules/dist/vee-vadidate.js

例1: 一个必填的email字段

<input v-validate="'required|email'" type="email" name="email">
<input v-validate="{ required: true, email: true }" type="email" name="email">

例2: 只包含英文字符的username字段

<input v-validate="'alpha'" type="text" name="username">
<input v-validate="{ alpha: true }" type="text" name="username">

例3: 校验长度的password字段

<input v-validate="'required|min:6'" type="password" name="password">
<input v-validate="{ required: true, min: 6 }" type="password" name="password">

注意:

字符串表达式两边有 “'”(单引号)。因为 Vue 指令会计算给定表达式的值,由于我们想要将它求值为一个字符串,所以需要用 “'”(单引号) 将它括起来,这意味着 v-

validate=“required” 将失败,因为 v-validate 将尝试在 Vue 实例上查找一个名为 ‘required’ 的 prop 或 method,而这很可能不存在,所以会失败。

<div class="column is-12">
    <label class="label" for="email">Email</label>
    <p class="control">
        <input v-validate data-rules="required|email" :class="{'input': true, 'is-danger': errors.has('email') }" name="email" type="text" placeholder="Email">
        <span v-show="errors.has('email')" class="help is-danger">{{ errors.first('email') }}</span>
    </p>
</div>

关于errors

errors.has,errors.first,errors是组件内置的一个数据模型,用来存储和处理错误信息,可以调用以下方法:

  • errors.first(‘field’) - 显示字段field的第一个出错信息
  • collect(‘field’) - 获取关于当前field的所有错误信息(list)
  • errors.has(‘field’) - 判断fileds字段是否检验有误
  • erros.all() - 显示所有的出错信息
  • errors.collect(‘field’) - 显示字段field的所有出错信息
  • errors.any() - 判断是否有错误
  • errors.clear() - 清除错误
  • errors.count() - 错误数量
  • errors.remove(String field) - 清除指定field的所有错误

6. 数据的校验

this.$validator.validate(‘field’); 校验单个字段
this.$validator.validateAll(); 表单整体校验
验证代码:
this.$validator.validateAll().then(function(result) {
 if (result) {
  //成功操作
 } else {
  // 失败操作
 }  
}

常用于校验成功后清除错误的提示信息:this.errors.clear();

7.自定义校验规则

1.直接定义

const validator = (value, args) => {
    // Return a Boolean or a Promise.
}
//最基本的形式,只返回布尔值或者Promise,带默认的错误提示

2.对象形式

const validator = {
    getMessage(field, args) { // 添加到默认的英文错误消息里面
        // Returns a message.
    },
    validate(value, args) {
        // Returns a Boolean or a Promise.
    }
};

3.添加到指定语言的错误消息

const validator = {
    messages: {
        en: (field, args) => {
            // 英文错误提示
        },
        cn: (field, args) => {
            // 中文错误提示
        }
    },
    validate(value, args) {
        // Returns a Boolean or a Promise.
    }
};

创建了规则以后,用extend 方法添加到 Validator里面

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)
    }
});
然后接可以直接把mobile当成内置规则使用了:
 
<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>

8. 实践

首先,我们先在src下创建 validate文件夹,在文件夹下创建 validate.js 和 validatorRulke.js

1. validate.js

//引入Vue
import Vue from 'vue';
//引入vee-valadiate插件
import VeeValidate,{ Validator } from 'vee-validate'
//Vue.use(VeeValidate);
Validator.locale = 'zh_CN'
// //引入进来的是vee-valadiate提供信息提示【中文的】
import zh_CN from 'vee-validate/dist/locale/zh_CN'

//  // 引入英文文件
import en from 'vee-validate/dist/locale/en'

import {attributesCh, attributesEn} from './validatorRule'

const config = {
  errorBagName: 'errors',
  fieldsBagName: 'fieldBags',
  // delay: 10000,
  locale: 'en',
  strict: true,
  enableAutoClasses: true,
  events: 'input|blur',
  inject: true
}
//使用插件
Vue.use(VeeValidate,config)


// //添加中文检验规则设置
Validator.localize('zh_CN', {
    messages: {
        ...zh_CN.messages, //提示语
        // required: (field) => field+"不能为空!",
    },
    attributes: attributesCh
})

//给VeeValidate插件提供【英文提示功能】
Validator.localize('en', {
  messages: {
    ...en.messages, //提示语
    // required: (field) => field+"不能为空!",
},
  attributes: attributesEn
})

//对象形式,
export function setMessage(validName, errMsgZh, errMsgEn, validate) {
    Validator.locale = 'en'
    Validator.extend(validName, {
      getMessage: (field, [args]) => {
       return errMsgEn
      },
      validate: validate
    })
    Validator.locale = 'zh_CN'
    Validator.extend(validName, {
      getMessage: (field, [args]) => {
        return errMsgZh
      },
      validate: validate
    })
 }

2.validatorRule.js

import {setMessage} from './validate'

setMessage('password', '密码必须是11到8位', 'password error', (value, [args]) => {
  const reg = /^\S{6,18}$/
  return reg.test(value)
})

setMessage('username', '姓名只能包括中文字或英文字母', 'username no yes', (value, [args]) => {
  const reg = /^([\u4e00-\u9fa5\s]|[a-zA-Z])*$/
  return reg.test(value)
})

// 别名中文
export const attributesCh = {
  username: '用户名',
  password: '密码'
}
// 别名英文
export const attributesEn = {
  username: 'username',
  password: 'password',
}

3.在main.js 中引入validate.js

//加载校验器
import '@/validate/validate'

4.form表单中应用

      <el-form-item prop="username">
          <el-input
            v-validate="'required|max:20'"
            data-cc-as = "账号"
            prefix-icon="el-icon-user"
            v-model="loginForm.username"
            placeholder="ID"
            name="username"
            autofocus/>
            <span v-show="errors.has('username')" class="error-style">*  {{ errors.first('username') }} </span>
        </el-form-item>
<el-form-item prop="password">
          <el-input
            v-validate="'required|min:5|max:10'"
            v-model="loginForm.password"
            prefix-icon="el-icon-unlock"
            placeholder="请输入密码"
            name="password"
         />
          <span v-show="errors.has('password')" class="error-style">*  {{ errors.first('password') }} </span>
        </el-form-item>
  • 2
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Vue 3 和 VeeValidate 是两个独立的库,可以一起使用来进行表单验证。下面是一些关于 Vue 3 和 VeeValidate 的基本信息: 1. Vue 3:Vue 3 是一款流行的 JavaScript 框架,用于构建用户界面。它提供了一套简洁的语法和强大的功能,使开发者可以轻松构建交互式的前端应用程序。 2. VeeValidateVeeValidate 是一个基于 Vue.js 的表单验证库。它提供了一组强大的验证规则和错误消息处理机制,方便开发者对表单进行验证和提示用户错误。 在 Vue 3 中使用 VeeValidate,你需要按照以下步骤进行设置: 1. 安装 VeeValidate: ``` npm install vee-validate@next ``` 2. 在你的 Vue 3 项目中导入 VeeValidate: ```javascript import { createApp } from 'vue'; import { createRouter, createWebHistory } from 'vue-router'; import { createI18n } from 'vue-i18n'; import { ValidationProvider, extend } from 'vee-validate'; import { required, email } from '@vee-validate/rules'; // 添加验证规则 extend('required', required); extend('email', email); const app = createApp(App); const router = createRouter({ history: createWebHistory(), routes, }); const i18n = createI18n({ locale: 'en', messages: { en: { validation: { required: 'This field is required.', email: 'Please enter a valid email address.', }, }, }, }); app.use(router); app.use(i18n); app.component('ValidationProvider', ValidationProvider); app.mount('#app'); ``` 3. 在你的 Vue 3 组件中使用 VeeValidate: ```vue <template> <ValidationProvider v-slot="{ errors }" rules="required|email" name="email"> <input v-model="email" type="text" placeholder="Email"> <span>{{ errors[0] }}</span> </ValidationProvider> </template> <script> import { ref } from 'vue'; export default { name: 'MyForm', setup() { const email = ref(''); return { email, }; }, }; </script> ``` 通过以上步骤,你可以在 Vue 3 中使用 VeeValidate 来进行表单验证。你可以根据自己的需要添加其他验证规则和自定义错误消息。希望对你有所帮助!如果还有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

半夏_2021

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值