In my last article, I covered the VueJs validation package VeeValidate. In part 2, we’re going to be talking about another popular validation package called Vuelidate. While VeeValidate took a template-based approach, Vuelidate is the exact opposite with a model-based approach.

Just like the last article, we’ll be looking at how we can use this package on a signup form. This will give you a clear idea of how you can use this on just about any form. So, let’s get to coding!

Installation

To install VeeValidate, open a terminal in the root of your Vue project, and run the following command:

npm install vuelidate --save

Next, we’ll add Vuelidate to Vue as a plugin. In src/main.js add the following:

import Vuelidate from 'vuelidate'
Vue.use(Vuelidate)

Form Validation

The way that a field gets validated is based on your model. The data property in export default contains the model (v-model) for your inputs. By importing the Vuelidate package, you’ll now have a new property you can add to export default called “validations”.

All you need to do is import the rules you need from the Vuelidate (Available Rules).

import { required, minLength } from "vuelidate/lib/validators";

Then, add a property to “validations” with the exact same name as your model properties. This will bind your validations to your model.

data: () => ({
 // Your Model
 name: ""

}),
//Your model validations
validations: {
 name: {
  required,
  minLength: minLength(4)
 }
}

Next, you’ll need to construct your form in the template with your inputs and errors.

<template>
 <div>
  <h2>Vuelidate Form</h2>
  <form @submit.prevent="submitForm">
   <input type="text" v-model="name" />
   <!-- display errors -->
   <div 
    class="error" 
    v-if="!$v.name.required && $v.name.$dirty">
     Field is required
   </div>
   <div
    class="error"
    v-if="!$v.name.minLength && $v.name.$dirty"
   >
    Name must have at least {{$v.name.$params.minLength.min}}
    letters.
   </div>
   <input type="submit" />
  </form>
 </div>
</template>

#javascript #vue #programming #vuejs #software-development #vuejs

VueJs Form Validation Part 2 — Vuelidate
2.75 GEEK