Vue3(ts)使用vee-validate表單校驗(yàn),自定義全局驗(yàn)證規(guī)則說明
更新時(shí)間:2024年04月22日 11:40:48 作者:Summer不禿
這篇文章主要介紹了Vue3(ts)使用vee-validate表單校驗(yàn),自定義全局驗(yàn)證規(guī)則說明,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
注意:這篇文章代碼里的樣式引入了tailwindcss
安裝并引入
- yarn add vee-validate
- 或者 npm i vee-validate --save
- 或者 pnpm add vee-validate
定義全局校驗(yàn)規(guī)則
在utils目錄下新建一個(gè)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é)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue中添加語音播報(bào)功能的實(shí)現(xiàn)
本文主要介紹了vue中添加語音播報(bào)功能的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-04-04
vue實(shí)現(xiàn)手機(jī)驗(yàn)證碼登錄
這篇文章主要為大家詳細(xì)介紹了vue實(shí)現(xiàn)手機(jī)驗(yàn)證碼登錄,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-11-11
Vuex拿到state中數(shù)據(jù)的3種方式與實(shí)例剖析
store是一個(gè)狀態(tài)管理工具(vueX中只有唯一 一個(gè)store),下面這篇文章主要給大家介紹了關(guān)于Vuex拿到state中數(shù)據(jù)的3種方式與實(shí)例剖析的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-09-09
vue3+vite實(shí)現(xiàn)低版本瀏覽器兼容的解決方案(出現(xiàn)白屏問題)
項(xiàng)目全線使用vue3的時(shí)候,自然使用的是配套更加契合的vite打包工具,于是自然而然會用到很多新的語法,本文給大家介紹了vue3+vite實(shí)現(xiàn)低版本瀏覽器兼容的解決方案(出現(xiàn)白屏問題),需要的朋友可以參考下2024-04-04

