Vue3实战笔记(04)--- 表单校验Vuelidate

62 篇文章 2 订阅
62 篇文章 2 订阅
本文介绍了如何在Vue3项目中使用Vuelidate进行表单数据验证,包括安装步骤、基础使用示例(如验证规则和自定义消息)、以及高级用法,帮助开发者快速掌握前端表单验证的最佳实践。
摘要由CSDN通过智能技术生成


前言

表单校验是前端开发中常见的任务,用于确保用户输入的数据满足特定的要求。在 Vue 3 中,你可以使用多种方法来进行表单校验,包括使用 Vue 自身的响应式系统和组合式 API,或者结合第三方库如 Vuelidate,巧了,我也选择使用Vuelidate。


一、安装Vuelidate

pnpm install @vuelidate/core @vuelidate/validators

使用实例:

import { reactive } from 'vue' // or '@vue/composition-api' in Vue 2.x
import { useVuelidate } from '@vuelidate/core'
import { email, required } from '@vuelidate/validators'

export default {
  setup () {
    const state = reactive({
      name: '',
      emailAddress: ''
    })
    const rules = {
      name: { required },
      emailAddress: { required, email }
    }

    const v$ = useVuelidate(rules, state)

    return { state, v$ }
  }
}

二、基础使用

经过实验总结,直接在实践中记录下几个实用技巧(解释都在js的注释里看看很容易就明白):

<template>
  <div>
    <v-img class="mx-auto my-6" max-width="228"
      src="https://cdn.vuetifyjs.com/docs/images/logos/vuetify-logo-v3-slim-text-light.svg"></v-img>

    <v-card class="mx-auto pa-12 pb-8" elevation="8" max-width="448" rounded="lg">
      <div class="text-subtitle-1 text-medium-emphasis">Account</div>

      <v-text-field density="compact" placeholder="Email address" prepend-inner-icon="mdi:mdi-email-outline"
        variant="outlined" v-model="state.name" :error-messages="v$.name.$errors.map(e => e.$message)"
        @input="v$.name.$touch" @blur="v$.name.$touch"></v-text-field>

      <div class="text-subtitle-1 text-medium-emphasis d-flex align-center justify-space-between">
        Password

        <a class="text-caption text-decoration-none text-blue" href="#" rel="noopener noreferrer" target="_blank">
          Forgot login password?</a>
      </div>

      <v-text-field :append-inner-icon="visible ? 'mdi:mdi-eye-off' : 'mdi:mdi-eye'" :type="visible ? 'text' : 'password'"
        density="compact" placeholder="Enter your password" prepend-inner-icon="mdi:mdi-lock-outline" variant="outlined"
        :error-messages="v$.password.$errors.map(e => e.$message)" @click:append-inner="visible = !visible"
        v-model="state.password" @input="v$.password.$touch" @blur="v$.password.$touch"></v-text-field>


      <v-card class="mb-12" color="surface-variant" variant="tonal">
        <v-card-text class="text-medium-emphasis text-caption">
          Warning: After 3 consecutive failed login attempts, you account will be temporarily locked for three hours. If
          you must login now, you can also click "Forgot login password?" below to reset the login password.
        </v-card-text>
      </v-card>

      <!-- <v-checkbox
        v-model="state.checkbox"
        :rules="[v => !!v || '请先勾选同意!']"
        label="Do you agree?"
        required
        ></v-checkbox> -->

        <!-- 自定义规则和消息 -->
      <!-- <v-checkbox v-model="state.checkbox" :error-messages="v$.checkbox.$errors.map(e => e.$message)"
        label="Do you agree?" required @change="v$.checkbox.$touch" @blur="v$.checkbox.$touch">
      </v-checkbox> -->

      <v-btn block class="mb-8" color="blue" size="large" variant="tonal" @click=login()>
        Log In
      </v-btn>

      <v-card-text class="text-center">
        <a class="text-blue text-decoration-none" href="#" rel="noopener noreferrer" target="_blank">
          Sign up now <v-icon icon="mdi:mdi-chevron-right"></v-icon>
        </a>
      </v-card-text>
    </v-card>
  </div>
</template>

<script setup lang='ts' name="Login">
import { Ref, ref } from 'vue'
import { reactive } from 'vue'
import { useVuelidate } from '@vuelidate/core'
import { email, helpers, minLength, required } from '@vuelidate/validators'
import { watch } from 'vue';

let visible = ref(false)
//初始化状态
const initialState = {
  name: '',
  password: '',
  email: 'sht@163.com',
  checkbox: false,
}

const state = reactive({
  ...initialState,
})

const mustBeCool = (value: any) => value != false
//验规规则
const rules = {
  name: { required: helpers.withMessage('用户名不能为空', required) },
  password: {
    required: helpers.withMessage('密码不能为空', required),
    minLength: helpers.withMessage('密码不能小于6位', minLength(6)),
  },
  email: { required, email },
  checkbox: { required, mustBeCool: helpers.withMessage('请点击同意', mustBeCool) },
}

//配置校验规则和初始化状态
const v$ = useVuelidate(rules, state)

let nameErr: Array<string | Ref<string>> = []
//清空
function clear() {
  v$.value.$reset()    
}
function login() {
  let validate = v$.value.$validate()
  console.log(v$.value.$error)
  console.log(v$.value.$invalid)
  console.log(validate)
  if (!v$.value.$error && !v$.value.$invalid) {//如果校验通过
	//校验通过了干点什么吧
  } else {
    //对象方式赋值错误信息
    //  nameErr = []  
    //  nameErr = v$.value.name.$errors.map(e => e.$message)
  }
  v$.value.password.$errors[0].$validator
}

watch(nameErr, (newValue, oldValue) => {
  console.log('watch 已触发', newValue)
})
</script>

三、高阶用法

//1、自定义message:

required: helpers.withMessage('密码不能为空', required)

//2、自定义规则:

const mustBeCool = (value: any) => value != false

//3、一些可能用到的值变量:

  // console.log(v$.value.$anyDirty)   被触摸了也是true
  console.log(v$.value.$error)
  console.log(v$.value.$invalid)
//4、执行校验:

v$.value.$validate()

总结

直接看官网和文档可能有点云里雾里,可以直接看基础用法,把代码跑一下就明白了。
官网以及文档:

https://vuelidate.js.org/

https://vuelidate-next.netlify.app/

  • 9
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值