Vuelidate Library Examples: Validate Your Vue Forms Like a Pro

Having a flawless user interface is one of the things that just can’t be ignored. You might have the most perfect system in the world, that users can’t live without it, but if the UX is bad, users would still be unhappy about the system. Vuelidate is one of the things that no Vue developer could live without. From all the many existing validation libraries, this one is the most popular and the most frequently used Vue.js validation library that is used in many different size projects. And there is a reason why it is used: it has a big interest from the community (over 5.6k stars on GitHub). For a Vue library this is not bad), is model-based, decoupled from templates, can be used for validating a bunch of things: computed values, Vuex getters. And of course – it has wonderful documentation. Today in this Vuelidate example we will gonna check how easy is to use the Vuelidate.

Do I Need a Frontend Validation?

Front-end validation is one of the things that are not just a recommendation, but a necessity. Not only it is needed for the purpose of security (unvalidated form might be exploited by hackers and it would affect the end-users), but it is also a must to provide a perfect UX. Let’s break everything into details – why should you use Vuelidate library for validating forms:

Frontend Validation Advantages
Frontend Validation Advantages
  • Security – we are not going into details about how not using a solution for Vue.js validation, such as the Vuelidate library makes a threat for your end-users, but the thing is, that it does create additional risk. It might not compromise your servers (if the backend validation in implemented correctly), but this might compromise your users. As everything happens in their browsers, not implemented validation (or improperly used, not to the best practices, Vuelidate package, also if the Vuelidate is not defined), might steal their credentials, make requests from their browsers to other websites, and so on.
  • User experience – consider this: you are a user that is filling a form for, let’s say, a car insurance request. In some systems for this purpose, you would need to authenticate yourself with your e-signature, bank account, etc. And some of the information would be prefilled (your name, surname, personal code). But let’s say that in this hypothetical situation you have to input everything manually: your personal information, contact information, information about the car model, engine, registration place. So you get the point – the form you are filling is huge. Imagine this – you click on the Submit button, and boom – an error. If there is no frontend validation you would not know what information you entered in the wrong format. What is worse, after the request all the information might not be saved – you might be redirected to the empty form. This is all because there is no frontend validation implemented. This might be solved with a Vuelidate library or any other.
  • Fewer requests to the backend – if the frontend validation is not in place, and Vuelidate is not working, each of the requests will travel directly to the webserver. And this would all result into an additional server bandwidth. If thousands of users are using your application daily, this is a significant bandwidth. Catching the errors on clients’ browser would not put the weight on your server.

Once again frontend validation is not a “good to have” feature – it is a must.

How to Install Vuelidate library

Vuelidate installation process is pretty straightforward. All you need to do is to have the npm and vue-cli installed. If you don’t have it, refer to this.

If you don’t have a project, create a new one by:

vue create vuelidate-test

In other case, if you have a project you want to install the Vuelidate to, after you are set, navigate to the directory of your project and install the Vuelidate package:

npm install vuelidate --save

This is probably the way-to go, as this is how it is explained in the official documentation. However, if you want to use the CDN, here is a way how you can do it.

We have the Vuelidate package installed, that’s great. But we also need to have a form on which we can test if everything works. Now this might not be a problem if you are trying to implement Vue form validation into existing project. But if you don’t have any form yet, let’s create a simple one. Let’s move on from the newly created project. Change the directory to the project’s directory: cd vuelidate-test. Let’s install Bootstrap as it will be used for styling our form:

npm install bootstrap-vue bootstrap --save

After the successful installation, import the installed packages. Open your vuelidate-test/src/App.vue file and add these lines after the import Vue from ‘vue’ line:

import BootstrapVue from "bootstrap-vue"
 import "bootstrap/dist/css/bootstrap.min.css"
 import "bootstrap-vue/dist/bootstrap-vue.css"
 Vue.use(BootstrapVue)

This is how it should look like right now:

Bootstrap added to the App.vue file
Bootstrap added to the App.vue file

Let’s move on to the actual form. We can ignore the HelloWorld.vue component and for the clarity of the tutorial let’s work with the App.vue file alone. Open the vuelidate-test/src/App.vue file and override everything:

<template>
   <div>
      <div class="row">
         <div class="col-md-4">
         </div>
         <div class="col-md-4 border-style">
            <div>
               <div class="form-group" :class="{ 'form-group--error': $v.username.$error }">
                  <label class="form__label">Username</label>
                  <input class="form__input" :value="username" @change="setUsername($event.target.value)"/>
               </div>
               <div class="error" v-if="!$v.username.between">Must be between {{$v.username.$params.between.min}} and {{$v.username.$params.between.max}}</div>
               <span tabindex="0">Blur to see changes</span>
            </div>
            <div class="form-group" :class="{ 'form-group--error': $v.password.$error }">
               <label class="form__label">Password</label>
               <input class="form__input" :value="passsword" @change="setPassword($event.target.value)"/>
            </div>
            <div class="error" v-if="!$v.password.between">Must be between {{$v.password.$params.between.min}} and {{$v.password.$params.between.max}}</div>
            <span tabindex="0">Blur to see changes</span>
         </div>
      </div>
      <div class="col-md-4">
      </div>
   </div>
</template>

<script>
import Vue from 'vue'
import BootstrapVue from "bootstrap-vue"
import "bootstrap/dist/css/bootstrap.min.css"
import "bootstrap-vue/dist/bootstrap-vue.css"
import { required, minLength } from 'vuelidate/lib/validators'

Vue.use(BootstrapVue)

export default {
  name: 'app',
   data() {
    return {
      username: '',
      password: ''
    }
  },
  validations: {
    username: {
      required,
      minLength: minLength(4)
    },
    password: {
      required,
      minLength: minLength(4)
    }
  },
  
  methods: {
    setUsername(value) {
      this.username = value
      this.$v.username.$touch()
    },
    setPassword(value) {
      this.password = value
      this.$v.password.$touch()
    }
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

Now let’s check if Bootstrap was installed successfully and if the form is served. Execute the npm run serve and go to the browser. If everything works, you should be able to access it by http://localhost:8080/. A form in the middle of the page should be displayed, validation should work.

Vuelidate vs VeeValidate

Even though Vuelidate is the most popular form validation library, it is not the only one. Actually there are many of them. Each of them has their own pros and cons. Let’s review one of the alternatives for Vuelidate.

Vuelidate vs Vee-Validate
Vuelidate vs Vee-Validate comparison of npm downloads

This is a great alternative for Vuelidate. In fact, it is even more popular than the Vuelidate. However, it does have only slightly more monthly downloads. Right now, it has more stars on GitHub than Vuelidate itself. If you are interested in trying this library, you should consider that it works differently than Vuelidate.

The main difference: VeeValidate is template-based validation, while Vuelidate is model-based validation. Vuelidate is validating the values, while VeeValidate validates the inputs. If that sounds confusing, imagine this. VeeValidate requires that the models are hooked to inputs with v-model. The main benefit of this is that it eligibles for more customization possibilities, abstraction for error generation. While the Vuelidate is more flexible, it can’t offer abstractions for error generation. But what does the Vuelidate library offers, is speed. However, keep in mind that you might need to use additional packages for tasks such as error generation.

Final Words

That’s it, now you are ready to use Vuelidate library.