Simplify Your Vue.js Forms: A Guide to Basic & Custom Validations with Vuelidate

Ilker Cetin
Insider Engineering
5 min readMay 14, 2024

Have you ever wanted to validate your project’s input values easily? In this article, we will examine some of the benefits of the Vuelidate package for Vue.js and how to apply it to your project. Let's dive in.

First of all, let me explain why we wanted to use Vuelidate in our project. We had been working on our project for a long time. Because of that, our front-end development had been done using Vue 2.x. We aimed to upgrade our project to Vue 3, but this operation required some time since there were many components.

Also, we were using a popular validator library that did not support Vue 3. Our goal was to move to a different library that supported Vue 3, without changing much code in our project while we migrate to Vue 3.

As a team, while we researched alternative validator libraries for Vue.js, we encountered Vuelidate, which supports both Vue 2.x and Vue 3 together.

A tip from Vuelidate document that shows its supported Vue versions
A tip from the Vuelidate document that shows its supported Vue versions

We checked its documention, and were pleased to see that its capabilities satisfied our use cases. We decided to use Vuelidate for our new validator that used Composition API.

You may think that if we use Vue with a version earlier than 2.7 then we do not use Composition API. But, there is a Composition API package that we can use in earlier Vue versions without an issue. But if you are using a Vue version higher than 2.7, you don’t need to worry about it because Composition API comes as a default. You can directly install and use the Vuelidate.

Adding Vuelidate to your project

If you are using Vue 2.7 or lower, you need to install the composition API package:

npm install @vue/composition-api
# or
yarn add @vue/composition-api

Then you need to register it inside your project:

import Vue from 'vue';
import VueCompositionAPI from '@vue/composition-api';

Vue.use(VueCompositionAPI);

Let's install Vuelidate on our project now, then we are ready to go:

npm install @vuelidate/core @vuelidate/validators

// OR

yarn add @vuelidate/core @vuelidate/validators

Validating Inputs

Let’s start with a basic validation for an input:

import { useVuelidate } from '@vuelidate/core' // Importing the vuelidate package
import { required } from '@vuelidate/validators' // Importing built-in validations

export default {
setup () {
return { v$: useVuelidate() } // We initialize the Vuelidate in setup as v$
},

data () {
return {
name: '', // We are initilazing the data that we want to validate
}
},

validations () {
return {
name: { required }, // Matches this.name
}
}
}
}

First of all, we need to initialize the variable that we want to validate. Then we declare our validation rules in the validations function. After we go through these steps, our variable is validated by Vuelidate.

In the example above, we used the required built-in validation of Vuelidate. This means that if our name variable is empty, an error is stored in the v$.name.$errors array.

Here’s a simple HTML to create a playground for your validation:

<div :class="{ error: v$.name.$errors.length }">
<input v-model="name">
<div class="input-errors" v-for="error of v$.name.$errors" :key="error.$uid">
<div class="error-message">{{ error.$message }}</div>
</div>
</div>

You can check all the built-in validators on this page: https://vuelidate-next.netlify.app/validators.html

Custom Validators

You checked the built-in validators but could not find a validation for a case for your project or you want to change its validation message. Don’t worry! Vuelidate lets you define your custom validators.

Here is how you can do it:

Changing the validator message

First, you need to import Vuelidate’s helpers function:

import { required, helpers } from '@vuelidate/validators';

Then you can change the validator message for your validation rule:

validations () {
name: {
required: helpers.withMessage('You need to enter a name to continue', required),
}
}

Creating your custom validator

Let's imagine you want to validate the image type that is uploaded to your website. We can create a custom validation for that purpose. First, create a validator.js file to create your custom validators inside of it. Then you can create a validator object like this:

export const validateImageType = {
$validator (file) {
const IMAGE_TAG_REGEX = /\.(jpg|jpeg|png)$/i;

return !(file.length === 0 || !IMAGE_TAG_REGEX.test(file.name));
},
$message: () => 'Wrong image type. Please upload a different image.',
};

As you can see, the $validator function is where we write our custom validation algorithm. It checks the image type here and returns true or false according to the file type. If it returns true, validation is correct. If it returns false, validation is incorrect.

$message function returns a custom validation message if the $validator function returns false.

Now let’s check how we can use this validator in our component.

First, you need to import this validator in your component as we import built-in validators:

import { validateImageType } from 'validators';

Once we import our custom validator, we can use it inside the validations like this:

validations () {
return {
profileImage: {
validateImageType,
},
}

Now let’s create a validator that takes parameters inside of it. Imagine we have different image upload inputs and their image sizes should be different from each other. We can handle this situation with a validator like this:

export const validateImageSize = size => ({
$validator (file) {
return file.size < size;
},
$message: () => `Image size can not be higher than ${size}kB`,
});

As you can see above, we created a function this time rather than an object. We expect it to get a size parameter now. Here is how you can use it:

import { validateImageType, validateImageSize } from 'validators';
validations () {
return {
profileImage: {
validateImageType,
validateImageSize: validateImageSize(512000),
},
}

As you can see, we passed a parameter to our validation and it validated our image size besides our image type. Remember that invalid validation information is written into the $errors array from the first invalid validation to the last invalid validation.

Conclusion

In this article, I wanted to show you how you can validate your inputs basically with the Vuelidate package and some of its benefits. The main reason for us to use it was its compatibility with both Vue 2.x and Vue 3 versions so we don’t have to change our validation structure while we migrate our project to Composition API. There are lots of use cases of Vuelidate that you can use. For a more advanced guide, please read the original document of Vuelidate here: https://vuelidate-next.netlify.app/

Thanks for reading, and have a good coding!

If you want to read more about frontend articles that our Front-end Developers write to strengthen your project, you can read the articles listed:

--

--