Vuelidate使用教程

Vuelidate使用教程

Vuelidate介绍

Vuelidate是一个轻量级的Vue 3/2表单校验库,下面的教程基于Vue3 Composition API、Vuelidate2、Vuetify3(3.0.0-beta.5)实现。

项目的代码地址如下:https://github.com/jyjdal/vuelidate-tutorial

安装

使用Node

npm install @vuelidate/core @vuelidate/validators

// 或者使用Yarn

yarn add @vuelidate/core @vuelidate/validators

使用CDN

<!-- Vue-->
<!--  For Vue 2 -->
<!--  <script src="https://cdn.jsdelivr.net/npm/vue@2"></script>-->
<!--  <script src="https://cdn.jsdelivr.net/npm/@vue/composition-api"></script>-->
<!--  For Vue 3 -->
<script src="https://cdn.jsdelivr.net/npm/vue@3"></script>
<!--  Vuelidate -->
<script src="https://cdn.jsdelivr.net/npm/vue-demi"></script>
<script src="https://cdn.jsdelivr.net/npm/@vuelidate/core"></script>
<script src="https://cdn.jsdelivr.net/npm/@vuelidate/validators"></script>

基本的表单校验

为了有一个比较好看的界面,这里使用Vuetify(3.0.0-beta.5)。

  1. 实现表单的界面
  2. 引入Vuelidate,添加校验规则并实现校验
  3. 展示错误信息

实现表单界面

这部分就是定义一个表单以及对应的几项数据,实现表单的页面布局

<template>
  <v-app>
    <v-main class="d-flex align-center">
      <v-form>
        <v-text-field
          v-model="formData.name"
          placeholder="Name"
          variant="solo"
          class="v-col-4 offset-4"
        ></v-text-field>
        <v-text-field
          v-model="formData.email"
          placeholder="Email"
          variant="solo"
          class="v-col-4 offset-4"
        ></v-text-field>
        <v-text-field
          v-model="formData.password.password"
          placeholder="Password"
          variant="solo"
          type="password"
          class="v-col-4 offset-4"
        ></v-text-field>
        <v-text-field
          v-model="formData.password.confirmation"
          placeholder="Confirmation"
          variant="solo"
          type="password"
          class="v-col-4 offset-4"
        ></v-text-field>
      </v-form>
      <v-btn class="v-col-4 offset-4" @click="submitForm">Submit</v-btn>
    </v-main>
  </v-app>
</template>

<script setup lang="ts">
import { reactive } from "vue";

const formData = reactive({
  name: "",
  email: "",
  password: {
    password: "",
    confirmation: "",
  },
});

function submitForm() {
  alert("Form submitted...")
}
</script>

基础表单布局

引入Vuelidate,添加校验规则,实现校验

  1. 定义校验的规则,Vuelidate内置了几个常用的校验器,详见:Validators | Vuelidate

    这里又几个注意事项:

    1. 校验规则要和表单的属性结构一致,不然会无法正确校验,比如下面的formData和rules,二者的结构需要一致
    2. 校验规则可以有空缺,比如下面规则中的name是可以注释掉的,email、password.password、password.confirmation同理
    3. 校验规则必须是一个computed,否则即使在某些情况下能够正常工作,但是仍然会有可能出现bug,比如下面的sameAs规则
    import { computed, reactive } from "vue";
    import { email, maxLength, required, sameAs } from "@vuelidate/validators";
    
    // 这里是表单属性
    const formData = reactive({
      name: "",
      email: "",
      password: {
        password: "",
        confirmation: "",
      },
    });
    
    // 校验的规则,需要注意上面的三个注意事项
    const rules = computed(() => {
      return {
        // required: 必填项, maxLength: 最大长度不超过函数参数的值, email: 符合电子邮箱的格式
      	// sameAs: 与某项必须一致(参数填formData里面的属性)
        name: { required, maxLength: maxLength(10) },
        email: { required, email },
        password: {
          password: { required },
          confirmation: {
            required,
            sameAsPassword: sameAs(formData.password.password),
          },
        },
      };
    });
    
  2. 引入Vuelidate

    在Vuelidate中,约定v$作为表单校验器的名字。

    这里需要注意的是,

    import useVuelidate from "@vuelidate/core";
    
    const v$ = useVuelidate(rules, formData);
    
  3. 实现校验

    首先从表单提交按钮开始,这里我们设置如果表单校验未通过,那么按钮无法点击。

    <v-btn
      class="v-col-4 offset-4"
      @click="submitForm"
      :disabled="submitButtonDisabled"
      >Submit
    </v-btn>
    
    const submitButtonDisabled = computed(() => {
      v$.value.$validate();
      return v$.value.$error;
    });
    

简单校验表单

这时如果表单校验通过,那么submit按钮可以点击(其中密码的值都是’123’)

展示错误信息

  1. 将错误信息提取出来,这里使用computed自动计算

    const nameErrors = computed<Array<string>>(() => {
      let errors: Array<string> = [];
      v$.value.name.$errors.forEach((error) => {
        errors.push(error.$message as string);
      });
      return errors;
    })
    
    const emailErrors = computed<Array<string>>(() => {
      let errors: Array<string> = [];
      v$.value.email.$errors.forEach((error) => {
        errors.push(error.$message as string);
      });
      return errors;
    })
    
    const passwordPasswordErrors = computed<Array<string>>(() => {
      let errors: Array<string> = [];
      v$.value.password.password.$errors.forEach((error) => {
        errors.push(error.$message as string);
      });
      return errors;
    })
    
    const passwordConfirmationErrors = computed<Array<string>>(() => {
      let errors: Array<string> = [];
      v$.value.password.confirmation.$errors.forEach((error) => {
        errors.push(error.$message as string);
      });
      return errors;
    })
    
  2. 通过Vuetify表单的error-messagesAPI将错误信息显示给用户

    <v-form>
      <v-text-field
        v-model="formData.name"
        placeholder="Name"
        variant="solo"
        class="v-col-4 offset-4"
        :error-messages="nameErrors"
      ></v-text-field>
      <v-text-field
        v-model="formData.email"
        placeholder="Email"
        variant="solo"
        class="v-col-4 offset-4"
        :error-messages="emailErrors"
      ></v-text-field>
      <v-text-field
        v-model="formData.password.password"
        placeholder="Password"
        variant="solo"
        type="password"
        class="v-col-4 offset-4"
        :error-messages="passwordPasswordErrors"
      ></v-text-field>
      <v-text-field
        v-model="formData.password.confirmation"
        placeholder="Confirmation"
        variant="solo"
        type="password"
        class="v-col-4 offset-4"
        :error-messages="passwordConfirmationErrors"
      ></v-text-field>
    </v-form>
    

提示错误信息

此时能够正确提示错误信息

自定义校验规则

基础校验器

基础的校验器其实可以看做一个返回boolean类型的函数。

这里引入一个新的场景,比如我们需要添加一个身份证的信息,格式必须要符合身份证的格式(这里按照18位计算)。

  1. 添加新的表单项

    <v-text-field
      v-model="formData.identity"
      placeholder="Identity"
      variant="solo"
      class="v-col-4 offset-4"
    ></v-text-field>
    
  2. 添加新的自定义校验器

    // 定义身份证号的正则表达式
    const identityRegex =
      /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
    
    // 定义校验器
    const identity = (value) => {
      return identityRegex.test(value);
    };
    
  3. 修改其他部分,使之能够正常工作

    const rules = computed(() => {
      return {
        name: { required, maxLength: maxLength(10) },
        email: { required, email },
        password: {
          password: { required },
          confirmation: {
            required,
            sameAsPassword: sameAs(formData.password.password),
          },
        },
        identity: { required, identity },  // 添加新的规则
      };
    });
    
    // 添加新的错误信息
    const identityErrors = computed<Array<string>>(() => {
      let errors: Array<string> = [];
      v$.value.identity.$errors.forEach((error) => {
        errors.push(error.$message as string);
      });
      return errors;
    });
    
    <v-text-field
      v-model="formData.identity"
      placeholder="Identity"
      variant="solo"
      class="v-col-4 offset-4"
      :error-messages="identityErrors"
    ></v-text-field>
    

针对身份证进行校验

带参数的校验器

带参数的校验器可以通过高阶函数的方式实现。这里我们以sameAs校验器为例,实现一个简单版本:

// 这样就可以将其应用在表单校验中
const mySameAs = (param: string) => (value: string) => value === param;

注意!!!如果需要传递响应式的参数,那么必须要使用withParams helper函数,参见:Custom Validators | Vuelidate

Helper functions

Vuelidate同时提供了一些工具类以便于用户自定义校验器,详见:Custom Validators | Vuelidate

自定义错误信息

现有的校验器还有一些不足:

  1. Vuelidate自带的校验器提供的错误信息都是英文的,但是有时候我们需要为用户提供中文的错误信息
  2. 自带的校验器无法提供错误信息

因此需要对原有的错误信息进行改造

这里以对姓名和身份证的校验为例,可以用Vuelidate提供的helpers中的withMessage:

import { helpers } from "@vuelidate/validators";

// 正则表达式同上
const identity = (value: string) => {
	return identityRegex.test(value);
}

const rules = computed(() => {
  return {
    name: {
      required: helpers.withMessage("姓名是必填项!", required),
      maxLength: helpers.withMessage("长度不能超过10!", maxLength(10)),
    },
    // 其余校验规则不变
    identity: {
      required,
      identity: helpers.withMessage("身份证不是合法的格式!", identity),
    },
  };
});

正确提示错误信息

至此,错误信息能够正确地展示。

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

OriginCoding

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

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

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

打赏作者

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

抵扣说明:

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

余额充值