Vue3(ts)使用vee-validate表單校驗,自定義全局驗證規(guī)則說明
更新時間:2024年04月22日 11:40:48 作者:Summer不禿
這篇文章主要介紹了Vue3(ts)使用vee-validate表單校驗,自定義全局驗證規(guī)則說明,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
注意:這篇文章代碼里的樣式引入了tailwindcss
安裝并引入
- yarn add vee-validate
- 或者 npm i vee-validate --save
- 或者 pnpm add vee-validate
定義全局校驗規(guī)則
在utils目錄下新建一個validate.ts文件(這里我使用的是ts,如果用js就創(chuàng)建js文件)
內(nèi)容示例如下:
import { defineRule } from 'vee-validate';
defineRule('required', (value: string ) => {
if (!value || !value.length) {
return '該字段不能為空';
}
return true;
});
defineRule('email', (value: string ) => {
if (!value || !value.length) {
return '郵箱地址不能為空';
}
if (!/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/.test(value)) {
return '請輸入有效的郵箱地址';
}
return true;
});然后在main.ts里引入
import '@/utils/validate'
使用
<template>
<Form class="flex flex-col text-white w-full px-8" @submit="onLogin()">
<div class="flex items-center pb-2 relative" style="border-bottom: 1px solid white">
<label>郵箱</label>
<Field class="border-none ml-3 bg-transparent focus:outline-none text-primary-smallTitle" name="email" rules="email" type="email" v-model="formState.email"></Field>
<ErrorMessage name="email" class="error" />
</div>
<button class="w-full text-white bg-purple-300 py-3 mt-12 border-none rounded-lg hover:bg-purple-400 cursor-pointer">登錄</button>
</Form>
</template><script lang="ts" setup>
import { reactive } from 'vue';
import { Form, Field, ErrorMessage } from 'vee-validate';
interface UserForm {
email: string;
}
const formState = reactive<UserForm>({
email: ''
});
const onLogin =() => {
console.log(formState);
};
</script><style scoped>
.error {
color: red;
position: absolute;
bottom: -20px;
left: 0;
font-size: 14px;
}
</style>總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue實現(xiàn)學(xué)生錄入系統(tǒng)之添加刪除功能
本文給大家?guī)硪粋€小案例基于vue實現(xiàn)學(xué)生錄入系統(tǒng)功能,代碼簡單易懂非常不錯,具有一定的參考借鑒價值,需要的朋友參考下吧2018-07-07
element-ui tree結(jié)構(gòu)實現(xiàn)增刪改自定義功能代碼
這篇文章主要介紹了element-ui tree結(jié)構(gòu)實現(xiàn)增刪改自定義功能代碼,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08
element?plus如何為表格某列數(shù)據(jù)文字設(shè)置顏色樣式
實習(xí)工作需要根據(jù)表格的狀態(tài)字段來設(shè)置列的樣式,所以這篇文章主要給大家介紹了關(guān)于element?plus如何為表格某列數(shù)據(jù)文字設(shè)置顏色樣式的相關(guān)資料,需要的朋友可以參考下2023-10-10

