While the most beginner-friendly approach to form validation in Vue.js might be through template-based forms, a much more flexible way is to validate the model instead. Model-based validation tends to be easier to understand and change for larger apps, moving the visual clutter from the template to the model and reducing it significantly. The most well-known library to accomplish this in Vue is through Vuelidate.
As usual, Vuelidate can be installed from NPM or Yarn.
Then, in your app bootstrap, enable the Vuelidate plugin.
To validate fields, add a definition object for properties in your data model to the validations property of your component. Then import validation functions from vuelidate/lib/validations (or custom ones you create). You will then be able to bind to the data property via v-model as usual. Validation information will be stored in this.$v[propertyName].
$v’s Schema:
Vuelidate provides these validators by default. They can be imported from vuelidate/lib/validators. If you’re using Webpack 2 or Rollup with tree shaking, any validators not used in your project will not be bundled with it.
A custom validator in Vuelidate is simply a function that returns a boolean or a promise that resolves to a boolean.
If you want to ensure that fields contain only the word “tom”, you might write a validator like this.
You might want to go a step further and allow a string to be specified that must be matched. In that case, just create a higher-order function that returns the validator function, like so.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!