Vue Form Validation with Vuelidate

Oğuz Ergül
2 min readNov 10, 2020

As a developer sometimes we are working with forms and these forms has some special rules. Required inputs, defining max or min character length, etc. In this case, we will use the vuelidate library for our validation works.

There are many ways for making your form validations. Validation packages are also one of them. I have already used a few packages like vee-validate or vue-validate but this package is very simple and you can easily implement your regex rules on your validation. Vuelidate is a simple and lightweight model-based validation for Vue projects.

Installation Vuelidate

npm install vuelidate --save
Form.vue / HTML

Validation errors will be shown as span elements and these tags have dynamic conditions. For each value you want to validate, you have to create a key inside validations options.

In Turkey, citizens have a personal ID number known as T.C. Number. This number has its own rules. Basically, the rule is: The units digit of the sum of the first ten digits is equal to the last digit. According to this rule, we are generating a validation function as you see down below.

This Regex code for using only English Characters. This is a custom rule made by me for name and surname inputs. Regex codes are using for finding replacing text characters.

The currently available validators and helpers include:

  • alpha
  • alphaNum
  • and
  • between
  • maxLength
  • minLength
  • or
  • required
  • sameAs

The biggest difference you will notice in Vuelidate is that the validations are completely decoupled from the template. It means that instead of providing rules for different inputs inside a template, you declare those rules for your data model. In our project, we have four different rules:

  1. Required
  2. ID Control
  3. Character Control
  4. Min Length Control
import { validationMixin } from “vuelidate”;import { required, minLength } from “vuelidate/lib/validators”;

We have imported our validation rules and validationMixins from the vuelidate. Then defined our data on the form block. Then for these fields, I have created validations rules separately. These validation rules will not be displayed until the button is pressed as we declared on our submitForm method.

As you see we have created our form component and validations are used in span elements. Now our App.vue includes a Form component.

Github Repo: https://github.com/ergloguz/vue-form-validation

If you want to see a live demo of this project you can use the link below:

“ I HOPE IT HELPS YOU. HAPPY HACKING :) ”

--

--