Vuelidate — Forms, Related Fields, and Nested Fields Validation

Image for post
Image for post
Photo by Karen Ciocca 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 validate forms with Vuelidate.

Form Submission

We can check a form’s validity before submission with Vuelidate.

To do this, we can check the $invalid state before sending any requests.

For example, we can write:

We have the @submit.prevent directive to run the submit method when we click on the submit button.

In the submit method, we run this.$v.touch() to trigger form validation.

Then we check the this.$v.$invalid property to see if the form is invalid or not.

Contextified Validators

We can check related fields with contextified validators.

For example, we can write:

We added the sameAs validator to the repeatPassword field with the string of the field we want to compare with as the argument.

This way, we can make sure that both the password and repeatPassword fields are the same.

Data Nesting

We can validate nested data.

If a children validator has $invalid set to true , then the parent validator will also have $invalid true .

For example, we can write:

We defined the nested fields in the object we return in data and in the validations object.

Then in the template, we just access the properties as we have them in the component code.

Conclusion

We can validate forms, related fields and nested fields 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