Language: JavaScript
Form Handling
VeeValidate was created to simplify form validation in Vue applications by providing a declarative approach and reactive validation feedback. It supports both template-driven and composition API approaches, making it flexible for different Vue setups.
VeeValidate is a form validation library for Vue.js that allows you to validate forms and inputs declaratively. It provides built-in validation rules, custom rules, and integrates seamlessly with Vue's reactivity system.
npm install vee-validate@nextyarn add vee-validate@nextVeeValidate provides the `useForm` and `useField` composables (composition API) or `ValidationProvider` and `ValidationObserver` components (template API) to handle form validation. You can define rules, validate fields on input or blur, and display error messages reactively.
import { useField, useForm } from 'vee-validate';
import * as yup from 'yup';
const { handleSubmit } = useForm();
const { value: email, errorMessage } = useField('email', yup.string().email().required());
const onSubmit = handleSubmit(values => console.log(values));Defines a field `email` with Yup validation. The form uses `handleSubmit` to handle submission.
<ValidationObserver v-slot="{ handleSubmit }">
<form @submit.prevent="handleSubmit(onSubmit)">
<ValidationProvider rules="required|email" v-slot="{ errors }">
<input v-model="email" />
<span>{{ errors[0] }}</span>
</ValidationProvider>
<button type="submit">Submit</button>
</form>
</ValidationObserver>Uses the template API to validate an email input and show error messages.
import { defineRule } from 'vee-validate';
defineRule('even', value => value % 2 === 0 || 'Value must be even');Defines a custom validation rule called 'even' that checks if a number is even.
const { value: password } = useField('password', yup.string().min(6).required());
const { value: confirmPassword } = useField('confirmPassword', yup.string().oneOf([password], 'Passwords must match'));Validates password and confirm password fields, ensuring they match.
defineRule('uniqueEmail', async value => {
const response = await fetch(`/api/check-email?email=${value}`);
const { available } = await response.json();
return available || 'Email already taken';
});Demonstrates asynchronous validation for checking if an email is already in use.
Prefer using the Composition API (`useForm` and `useField`) for new Vue 3 projects.
Use Yup or Zod schemas for complex validations.
Display error messages reactively next to input fields.
Use custom rules for business-specific validations.
Validate on blur or input to provide instant feedback.