Open In App

How to Validate Data using validator Module in Node.js ?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

The Validator module is popular for validation. Validation is necessary to check whether the data is correct or not, so this module is easy to use and validates data quickly and easily. 

Feature of validator module:

  • It is easy to get started and easy to use.
  • It is a widely used and popular module for validation.
  • Simple functions for validation like isEmail(), isEmpty(), etc.

Installation of validator module:

You can visit the link Install validator module. You can install this package by using this command.

npm install validator

After installing the validator module you can check your validator version in the command prompt using the command.

npm version validator

After that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.

node index.js

Project Structure:

project structure

Filename: index.js 

javascript




const validator = require('validator')
 
// Check whether given email is valid or not
let email = 'test@gmail.com'
console.log(validator.isEmail(email))  // true
email = 'test@'
console.log(validator.isEmail(email))  // false
 
// Check whether string is in lowercase or not
let  name = 'geeksforgeeks'
console.log(validator.isLowercase(name))  // true
name = 'GEEKSFORGEEKS'
console.log(validator.isLowercase(name))  // false
 
// Check whether string is empty or not
let name = ''
console.log(validator.isEmpty(name))  // true
name = 'geeksforgeeks'
console.log(validator.isEmpty(name))  // false
 
// Other functions also available in
// this module like isBoolean()
// isCurrency(), isDecimal(), isJSON(),
// isJWT(), isFloat(), isCreditCard(), etc.


Steps to run the program:

Make sure you have to install the express and validator modules using the following commands:

npm install validator
npm install express

Run the index.js file using the below command:

node index.js

Output:

Output of above command

So this is how you can use the validator module for validation. There are also other modules available in the market for validation like hapi-joi, express-validator, etc.


Last Updated : 27 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads