How to Validate Data Using Validator.js?

In every website of today’s world, the most common and useful requirement is to validate data that is passed as input by the user. Whether it’s filling out a form to create a new account or logging in to your old account, data validation is a must. We can never just rely on a user that will surely enter the correct input. We have to be extra careful on our side to make sure the user has entered the correct input, or else notify the user about the correct form of input. The most helpful tool available for browsers and nodes is validator.js. We will now discuss what is validator.js, and how you can validate data using validator.js.

What is Validator.js?

Validato.js is a data validation module. It is a npm module that is inspired by the Laravel framework’s validator. It is a library that allows different types of validation methods to be used in your JavaScript. The main advantage of using validator.js is that it can be used in both browser and node side. It easily allows you to validate data that is entered by the user as input, avoiding any further processing errors that can be caused by bad input.

Let’s see which are the major advantages of using Validator.js:

  • It works for both browser and node.
  • The standardized and easily readable validation rules.
  • ES6 support.
  • Error messages in multiple languages.
  • Common JS support

How to Install Validator.js Module?

Validator.js is a npm module and you can install it through any of the below mentioned ways.

  • Enter the code below to install it using npm
npm install validatorjs
  • Code to install it using yarn
yarn add validatorjs
  • Enter the code below to install it using bower
$ bower install validaator-js

You can import the validator.js in various platforms as below:

  • In browser side:
<script src=”validator.js”></script>
  • For Node.js for ES5 support:
let Validator = require(‘validator.js’);
  • In Node.js for ES6 support:
Import * as Validator from ‘validatorjs’;

How to Validate Data Using Validator.js?

You can use the validator module to validate your data by the following below syntax:

Let validate= new Validator(data, rules [,customErrorMessages])

In the above code, validate is used as a variable name to point out the newly created validator. data refers to the data which is to be validated. Validation is the set of rules that you want the validator to follow. customErrormessages is an optional parameter that can be used if you want to display a custom message if the user enters bad input.

Example: Enter the code below to check if the entered name is correct and age is above 18.

let validate= new Validator({ name: ‘Man’, age:22},{name:’size:3’, age:’min:18’});

Here, in the above code, as stated the first curly bracket consists of the data that is to be validated consisting of the name and age. The second set of curly brackets consist of the rules that should be followed. Don’t worry ‘size:3’ and ‘min:18’ are called validation rules, that we are going to study below. We have not included any custom error messages for now. We will also discuss below different types of error messages to return.

Which are the Different Validation Rules?

Here we have listed various validation rules along with the form of input in order to pass the test and use of each rule.

Validation ruleCondition for field value to pass the validation testUsage
acceptedValue must be yes, on, 1 or TrueFor ‘Terms and service” checkbox
after:dateValue must have date after given dateFor date of birth
alphaValue must contain only alphabetsFor any type of name field
alpha-numValue must have alpha-numeric charactersFor password with only alpha-numeric characters
dateValue must be a JavaScript Date objectFor any kind of date field
digits:valueValue must be numeric and should have exact length of ‘value’For mobile number
emailValue must be in email formatFor e-mail address field
integerValue must be in integer formatFor field requiring only numbers
inValue must be in given list of valueFor drop down menu
requiredValue must not be null or field must not be emptyFor fields which are compulsory to have a value
size:valueValue must have size equal to stated “value”For fields requiring specific length of input
urlValue must be in url formatFor url fields
min:valueValue must be greater than stated “value”For age related fields
max:valueValue must be less than stated “value”For maximum number of characters
confirmedThe two mentioned fields should have same valueIn fields like password and confirm password

How to Register Custom Validation Rules?

You can easily register your own validation rule with a specified name that you can use in place of that name using the code given below:

Validator.register(rule_name, validity_function, custom_errormessage)

Here,

rule_name: The name of the rule that you will use later

validity_function: The function that will check if the input value is correct and return true if so, otherwise False

custom_errormessage: The custom error message that you want to display.

Which are the Ways to Display Error Messages When Validation Fails?

Once a particular field fails to pass the validation test, our next step is to return an error message which can be customized or using the inbuilt error instances in errors property object. The various methods and properties on errors property object are:

  • .first(attribute): returns the first error message for given attribute
  • .get(attribute):returns the array of error messages of given attribute
  • .all():returns an object containing all error messages for all failing attributes
  • .errorcount: The total number of error messages.

Example: enter the code below to get first error message if email is wrong.

let validate= new Validator(input, rules);
validate.passes();
validate.fails();
validate.errors.get(‘email’)

Here, if the validation of email attribute fails, then it will return the first error message of email attribute.

In above example, validate.passes() returns true if the result passes and validate.fails() returns true if result fails and false otherwise.

Conclusion

Validation.js can act as a very important tool in your web development part, where you require to test whether the input by your user is of the required processing format or not. I hope the above article has enhanced your knowledge regarding what validator.js is and how to validate data.

Which feature of validator.js attracts you the most? Do tell us in comments below!!

Some links on this page are affiliate links. This means that if you choose to make a purchase, we may earn a small commission at no extra cost to you. For more information, Go here

Leave a Reply

Your email address will not be published.