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:

  • Make sure you are getting the right input from the user
  • Make sure the input is in the correct format

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.

Getting Started

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.

Validating Form Fields

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:

  • name
  • email
  • website

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:

  • name – is required and must be greater than 6 characters and less than 20 characters
  • email – is required and must be a valid email (e.g. mail@example.com)
  • website – is not required but if it’s entered, it must be a valid URL (e.g. http://example.com)

Let’s have a go at validating each field one after the other.

#tutorials #vue #form validation #programming

Validating Vue.js Forms Using Vuelidate
11.15 GEEK