Thanks to Vue’s reactivity model, it’s really easy to roll your own form validations. This can be done with a simple method call on the form submit, or a computed property evaluating input data on each change.
Using your form validation can quickly become cumbersome and annoying, however, especially when the number of inputs in the form increase, or the form structure gets more complicated e.g. multi-step forms.
Thankfully, there are great validation plugins for Vue like Vuelidate. In this article, we’ll be looking at how Vuelidate can be used to simplify:
- Validation
- Multi-step form validation
- Child component validation
- Error messages
We’ll also see how the Vuelidate-error-extractor plugin can be used to simplify error message display per input, or as an error summary above or below the form.
Basic validation with Vuelidate
Vuelidate is data-model oriented, meaning validation rules are added to a validations object in the component definition, rather than being added directly to input elements in the DOM.
The structure must resemble that of the form object, but the number of validation rules can be dynamic and change depending on which fields need validation.
export default {
name: "FormComponent",
data() {
return {
form: {
name: "",
email: ""
}
};
},
validations: {
form: {
name: { required },
email: { required, email }
}
}
...
};
Here’s a live example:
read more