Getting Started with Form Validation with Vuelidate

Image for post
Image for post
Photo by Tavis Beck on Unsplash

Vue.js doesn’t come with any form validation capabilities by default.

Therefore, we need to add our own form validation library or with our own code.

In this article, we’ll look at how to get started with adding form validation with Vuelidate.

Getting started

We can install the package by running:

Then in main.js , we add:

to add the Vuelidate plugin.

Alternatively, we can also write:

to add the validationMixin from Vuelidate globally.

We can also require the packages with:

Now we can use validation with our code.

For example, we can write:

to add our validation with Vuelidate.

We access everything we need with the $v variable since we registered the plugin.

Then the errors can be accessed with the $v.age and $v.name properties.

between has the between validation state.

If it’s truthy, then it’s valid.

Likewise, we have the required and minLength properties with those validation states.

We added the validations with the name and age properties to set the validation rules.

To make the validation work, we’ve to set the v-model directive to the correct value.

$v.name.$model is the model for the name state.

And $v.age.model is the model for the age state.

The $error property has the errors.

Without v-model

We can use Vuelidate without setting v-model to the values provided by Vuelidate.

To do that, we add extra methods to set the values:

We set the v-model to the name and age states.

And we added the setName and setAge methods to set those values to the name and age states.

And we call $touch to trigger the validation.

Conclusion

We can add basic form validation capabilities to a Vue app with Vuelidate.

Written by

Web developer. Subscribe to my email list now at http://jauyeung.net/subscribe/. Email me at hohanga@gmail.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store