Note: The styles in this article introduce tailwindcss
Install and introduce
- yarn add vee-validate
- or npm i vee-validate --save
- Or pnpm add vee-validate
Define global verification rules
Create a new file in the Utils directory (I am using ts here, if you use js, you will create a js file)
Examples of the content are as follows:
import { defineRule } from 'vee-validate'; defineRule('required', (value: string ) => { if (!value || !) { return 'This field cannot be empty'; } return true; }); defineRule('email', (value: string ) => { if (!value || !) { return 'The email address cannot be empty'; } if (!/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/.test(value)) { return 'Please enter a valid email address'; } return true; });
Then introduce it in
import '@/utils/validate'
use
<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>Mail</label> <Field class="border-none ml-3 bg-transparent focus:outline-none text-primary-smallTitle" name="email" rules="email" type="email" v-model=""></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">Log in</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 =() => { (formState); }; </script>
<style scoped> .error { color: red; position: absolute; bottom: -20px; left: 0; font-size: 14px; } </style>
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.