DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Top React Libraries for Data-Driven Dashboard App Development
  • How to Build a Concurrent Chat App With Go and WebSockets
  • How JavaScript DataTable Libraries Address Challenging Requirements in Web Data Management
  • React, Angular, and Vue.js: What’s the Technical Difference?

Trending

  • Medallion Architecture: Efficient Batch and Stream Processing Data Pipelines With Azure Databricks and Delta Lake
  • How AI Agents Are Transforming Enterprise Automation Architecture
  • Understanding IEEE 802.11(Wi-Fi) Encryption and Authentication: Write Your Own Custom Packet Sniffer
  • Mastering Fluent Bit: Installing and Configuring Fluent Bit on Kubernetes (Part 3)
  1. DZone
  2. Data Engineering
  3. Data
  4. Validation Forms in Vue.js Apps Using Vuelidate library

Validation Forms in Vue.js Apps Using Vuelidate library

By 
Yuri Mednikov user avatar
Yuri Mednikov
·
Apr. 01, 20 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
16.0K Views

Join the DZone community and get the full member experience.

Join For Free

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
 




xxxxxxxxxx
1


 
1
npm install vuelidate --save



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
 




xxxxxxxxxx
1
19


 
1
data() {    
2
  return {        
3
    signupRequest: {            
4
      email: '',            
5
      password: '',            
6
      confirmPassword: '',            
7
      firstName: '',            
8
      lastName: ''        
9
    }    
10
  } 
11
}, validations: {    
12
  signupRequest: {        
13
    email: {},        
14
    password: {}.        
15
      confirmPassword: {},        
16
    firstName: {},        
17
    lastName: {}    
18
  } 
19
}



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
 




xxxxxxxxxx
1
19


 
1
import {minLength, maxLength, required} from 'vuelidate/lib/validators' 
2

          
3
//.. 
4
validations: {    
5
  SignupRequest: {        
6
    password: {            
7
      required,             
8
      minLength(6)        
9
    },        
10
    firstName: {            
11
      required,             
12
      minLength(3),             
13
      maxLength(100)        
14
    },        
15
    lastName: {            
16
      required,            
17
      minLength(3),             
18
      maxLength(100)        
19
    }    
20
  } 
21
}



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
 




xxxxxxxxxx
1
10


 
1
import {required, email} from 'vuelidate/lib/validators' 
2
//... 
3
validations: {    
4
  SignupRequest: {        
5
    email: {            
6
        required, 
7
        email        
8
    }    
9
  } 
10
}


`

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.
app Form (document) Vue.js Library Data Types JavaScript Data (computing)

Opinions expressed by DZone contributors are their own.

Related

  • Top React Libraries for Data-Driven Dashboard App Development
  • How to Build a Concurrent Chat App With Go and WebSockets
  • How JavaScript DataTable Libraries Address Challenging Requirements in Web Data Management
  • React, Angular, and Vue.js: What’s the Technical Difference?

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!