{{announcement.body}}
{{announcement.title}}

Validation Forms in Vue.js Apps Using Vuelidate library

DZone 's Guide to

Validation Forms in Vue.js Apps Using Vuelidate library

In this article, we discuss how to use Vuelidate, a Vue.js form validation module to keep you from rewriting simple validation code.

· Web Dev Zone ·
Free Resource

Hello! One of the most common tasks in software development is input validation. Any app has different forms that submit some data, and we want to check numerous conditions: that fields are not empty and that they have a proper format (like emails), length, and so on. Yes, we can do it manually, but this is not the best path. It is better to use a specific validation library. For Vue.js apps, the popular choice is Vueildate. In this post, we will see how to install it to your Vue apps, how to use it, and observe the most important built-in validators.

What Is Vuelidate?

Let have a simple example. You’re building a signup form. You want to check that user provides a correct input, like:

  • Password has a minimal length of six characters.
  • All fields are filled.
  • Email has a valid format.
  • etc.

You can do this manually, but it is not the best route to follow. First, is that you will find yourself in a forest of nested if-else constructs, that you most probably could not understand after a week or two. Next, even small additions will bring a lot of changes. This is always safer to rely on an external validation library. For Vue.js applications, there are several choices, but one of most used is Vuelidate.

Installation

You can install Vuildate using your package manager CLI or from Vue UI’s dependencies tab. Let's check how to do it using NPM:

Shell
 







Then, you need to import Vuelidate in your src/main.js to use Vuelidate globally in all app’s components:

JavaScript
 




xxxxxxxxxx
1


 
1
import Vue from 'vue' 
2
import Vuelidate from 'vuelidate' //.. 
3
 
          
4
Vue.use(Vuelidate)



The last thing to do is to create validation object inside components and import required validators (will see this in next sections). You can call Vuelidate by this.$v instance.

Data() Function and Validations Object

Vueildate library uses a model-based validation. What does it mean? We need to add validation conditions to data() model fields. Yes, we can’t do this directly as data comes from Vue. Therefore, we create a new object, validations. Let's return to the previous example:

JavaScript
 







So, we have a model, SignupRequest, which corresponds to data we want to send to the server. We want to assert that all fields are filled and not only filled, but with specific requirements, like format or length. We create a validations object that mimimcs the data model. (Well, it does not have to copy all data model, but strictly the data model you want to validate). 

Each field provides in square brackets validators. You can use both built-in validators or create your own (however in this post we will follow only built-in validators).

Let say you want to check that all fields are filled. For this, we use the required validator. Import it and add it to the validations object:

JavaScript
 




xxxxxxxxxx
1
10


1
import {required} from 'vuelidate/lib/validators' 
2
 
          
3
export default { //... 
4
  data() {    
5
    return {        
6
      signupRequest: {            
7
        email: '',            
8
        password: '',            
9
        confirmPassword: '',            
10
        firstName: '',            
11
        lastName: ''        
12
      }    
13
    } 
14
  }, validations: {    
15
    signupRequest: {        
16
      email: {required},        
17
      password: {required}.        
18
      confirmPassword: {required},        
19
    firstName: {required},        
20
    lastName: {required}    
21
  } 
22
}
23
//.. }



Next, we actually need to call Vueildate to assert conditions.

Calling Vuelidate Assertions

Let's create a method that will submit our signup form:

JavaScript
 




xxxxxxxxxx
1


1
//.. 
2
methods: {    
3
  doSignup(){     
4
  } 
5
}



Here, we need to call Vueildate to assert specified conditions and perform a logic based on two variants:

  • Form is valid.
  • Form is invalid.

This is a sample implementation:

JavaScript
 




xxxxxxxxxx
1
10


1
methods: {    
2
  doSignup(){        
3
    this.$v.$touch()        
4
    const isInvalid = this.$v.$invalid        
5
    
6
    if (isInvalid){            
7
      // display error message            
8
      alert('Please check all fields!')        
9
    } else {            
10
      console.log('Form is correct')            
11
      // submit to server        
12
    }    
13
  } 
14
}



This is the most general approach that touches our form and checks that all fields are valid acording to specified condtions. Although, we can validate each value separately. For example, it helps us to hightlight missed fields. The generic pattern is:

JavaScript
 




xxxxxxxxxx
1


1
$v.[property-name].[validator]



Let's say we use Bulma:

HTML
 




xxxxxxxxxx
1
10


1
<div>    
2
  <div class="field">        
3
    <div class="control">            
4
      <input class="input" v-model="email" type="email" v-bind:class="{'is-     
5
       danger': !$v.email.invalid}">        
6
    </div>    
7
  </div>    
8
  <div class="field">        
9
    <div class="control">            
10
      <input class="input" v-model="password" type="password" v-bind:class="{'is
11
       danger': !$v.password.invalid}">        
12
    </div>    
13
  </div> 
14
</div>



So, this way we can bind is-danger class to input fields if data is missed. Next, let's see the most important built-in validators.

Built-in Validators

From a technical point of view, validators are conditions that are used by Vuelidate to assert the data model. In this section, we will look at the most common and used built-in validators in Vueildate.

required

We already checked this validator. It confirms that the field isn't empty. It also goes to cases when the field is a string value that contains only whitespaces and also for empty arrays. It does not have any paramaters and is very easy to use:

JavaScript
 




xxxxxxxxxx
1


1
import {required} from 'vuelidate/lib/validators' 
2
//.. 
3
validations: {    //..    
4
  firstName: {required},    
5
  lastName: {required}
6
}



sameAs

In our example, we have two fields, password and confirmPassword that, according to the app’s logic should be equal. Of course, we can do naive validation using vanilla JS:

JavaScript
 




xxxxxxxxxx
1


 
1
const passwordsSame = this.signupRequest.password === this.signupRequest.confirmPassword 
2
 
          
3
if (passwordsSame){    
4
    //.. 
5
} else {    
6
    //.. 
7
}



However, Vueildate has the sameAs validator that verifies an equality of the field to the given property. The code snippet below demonstrates how to use sameAs:

JavaScript
 




xxxxxxxxxx
1
10


 
1
import {required, sameAs} from 'vuelidate/lib/validators' 
2
//.. 
3
  validations: {    
4
    signupRequest: {        
5
      //..        
6
      password: {required},        
7
      confirmPassword: {            
8
        required,            
9
        sameAs('signupRequest.password')        
10
      }    
11
    } 
12
  }
10
      }    



NB we can combine multiple validators for the same field. For sameAs, we provide as an argument a name of the property we want to be equal with – in this case, it is signupRequest.password.

minLength/maxLength

This two validators assert the field’s length – either not less than (minLength) or not more than (maxLength). Both accepts as an argument an integer value of length. Works for strings and arrays.

JavaScript
 







Data Type Validators

This group includes several validators that check if the field is of the required data type. As an example, if we have an [invoice form](), we want to be sure that the user enters only numbers in a rate or amount fields. For that, we can utilize decimal and integer validators. Let's observe what do we have here:

  • integer: checks that field is an integer.
  • decinal: checks that field is a decimal.
  • numeric: checks that field is a numeric (both integer or decimal).
  • alpha: checks that field consists only from alphabet characters.
  • alphaNum: checks that field is alphanumeric (letters and digits).

Let add a new field to our model – age. We want that it is an integer:

JavaScript
 




xxxxxxxxxx
1
10


1
import {required, integer} from 'vuelidate/lib/validators' 
2
//.. 
3
validations: {    
4
  signupRequest: {        
5
    //..        
6
    age: {            
7
      required,            
8
      integer        
9
    },        
10
    password: {            
11
      required,             
12
      minLength(6),            
13
      alphaNum        
14
    }    
15
  } 
16
}



Email

The next validator we will observe here is email. It checks that a field is a valid email (of valid format, but it does not mean that this email actually exists – you have to find it out on the server-side).

JavaScript
 






`

Range Validators

Finally, let's overview what I call as a group, range validators. It includes three functions:

  • minValue(value): validates that the field is higher than a provided value
  • maxValue(value): validates that the field is lower than a provided value
  • between(a,b): validates that the field is between a and b values, both are included.

These validators work with numbers and dates. The code snippet below demonstrates the use of range validators:

JavaScript
 




xxxxxxxxxx
1
10


 
1
import {required, integer, minValue, maxValue} from 'vuelidate/lib/validators' 
2
//.. 
3
validations: {    
4
  signupRequest: {        
5
    //..        
6
    age: {            
7
      required,            
8
      integer,            
9
      minValue(18),            
10
      maxValue(100)        
11
    }    
12
  } 
13
}



Conclusion

In this post, we talked about Vueildate, a popular validation library for Vue.js applications. We observed an installation process and how to make Vueildate work (e.g. assert data model). We also checked the most common built-in validators.

References

  • Markus Oberlehner Vue.js Form Validation with Vuelidate (2018), read here.
  • Sarah Drasner Form Validation in Under an Hour with Vuelidate (2019) CSS-Tricks, read here.
Topics:
javascript, tutorial, vue form validation, vue framework, vue.js, web dev

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}