Getting user input is crucial for many web apps as it enables the web app to give the user a more personalized experience. However, getting user input is not so straightforward because you have to:
Ensuring that the input given by a user is in the right format is known as Form validation. In this article, we’ll cover how to validate Vue.js forms using a library called Vuelidate.
Create a new Vue project by running the following command in your terminal:
vue create validate-vue-forms
BashCopy
Select the default settings and install the dependencies. After it’s done, switch to the project directory and install vuelidate like so:
yarn add vuelidate
BashCopy
Then add it to your Vue app:
// main.js
import Vuelidate from ‘vuelidate’
Vue.use(Vuelidate)
JavaScriptCopy
Or you can import it directly in the components where it is required:
import { validationMixin } from 'vuelidate'
export default {
...
mixins: [validationMixin],
validations: { ... }
...
}
JavaScriptCopy
We’ll be importing it using the latter and importing vuelidate directly in our component.
When validating forms, generally and in Vue.js, we need to define exactly what our needs are which would guide our validation logic. For the purposes of this tutorial, we’ll use a simple form. The form will contain the 3 fields:
We need to determine which fields will be required and which won’t be, the data type expected and conditions for what a “correct” input will be for each field. Let’s work with the following set of rules:
Let’s have a go at validating each field one after the other.
#tutorials #vue #form validation #programming