Course Content
VUE Tutorial
About Lesson

Using Vuelidate for Form Validation

Form validation is a crucial aspect of web development, ensuring that user inputs are accurate and meet specified criteria. In Vue.js, achieving effective form validation can be streamlined with the help of Vuelidate, a lightweight validation library. In this post, we’ll explore the integration and usage of Vuelidate for form validation in Vue.js applications.

Why Vuelidate?

Before diving into the implementation details, let’s briefly discuss why Vuelidate stands out for form validation in Vue.js. Vuelidate offers a declarative way to validate your data, seamlessly integrating with Vue components. It’s lightweight, efficient, and provides real-time validation feedback to users, enhancing the overall user experience.

Setting Up Vuelidate

The first step is to install Vuelidate in your Vue.js project. Use the following command:

npm install @vuelidate/core @vuelidate/core @vuelidate/vue@next

Once installed, you can import and use Vuelidate in your components.

Basic Usage

1. Importing Vuelidate

import { useVuelidate } from '@vuelidate/core';
import { withValidation } from '@vuelidate/core';
import { required, email } from '@vuelidate/validations';

2. Setting Up Validation Rules

const validations = {
email: { required, email },
password: { required, minLength: minLength(6) },
};

3. Applying Validation to Your Component

export default {
setup() {
const { value, meta, isValid } = useVuelidate(validations);

return {
value,
meta,
isValid,
};
},
};

Real-time Feedback

4. Displaying Validation Messages

<template>
<form @submit.prevent="handleSubmit">
<label>Email:</label>
<input v-model.trim="value.email" />
<p v-if="meta.email?.$pending">Validating...</p>
<p v-if="meta.email?.required && meta.email.$params.required">Email is required.</p>
<p v-if="meta.email?.email && meta.email.$params.email">Invalid email format.</p>

<label>Password:</label>
<input type="password" v-model.trim="value.password" />
<p v-if="meta.password?.required && meta.password.$params.required">Password is required.</p>
<p v-if="meta.password?.minLength && meta.password.$params.minLength">Password must be at least 6 characters.</p>

<button :disabled="!isValid">Submit</button>
</form>
</template>