Validation in node.js can be easily done by using the express-validator module. This module is popular for data validation. There are other modules available in market like hapi/joi, etc but express-validator is widely used and popular among them.
Steps to install express-validator module:
- You can install this package by using this command.
npm install express-validator
- After installation, you can check your express-validator module version in command prompt using the command.
npm version express-validator
- After that, you can just create a simple data as shown below to send the data to the server.
Filename: SampleForm.ejs
<!DOCTYPE html><html><head><title>Validation using Express-Validator</title></head><body><h1>Demo Form</h1><formaction="saveData"method="POST"><pre>Enter your Email : <inputtype="text"name="email"> <br>Enter your Name : <inputtype="text"name="name"> <br>Enter your Number : <inputtype="number"name="mobile"> <br>Enter your Password : <inputtype="password"name="password"> <br><inputtype="submit"value="Submit Form"></pre></form></body></html>chevron_rightfilter_none - After that, you can just create a file, for example index.js as show below:
Filename: index.js
const { check, validationResult }= require('express-validator');const bodyparser = require('body-parser')const express = require("express")const path = require('path')const app = express()varPORT = process.env.port || 3000// View Engine Setupapp.set("views", path.join(__dirname))app.set("view engine","ejs")// Body-parser middlewareapp.use(bodyparser.urlencoded({ extended:false}))app.use(bodyparser.json())app.get("/",function(req, res) {res.render("SampleForm");})// check() is a middleware used to validate// the incomming data as per the fieldsapp.post('/saveData', [check('email','Email length should be 10 to 30 characters').isEmail().isLength({ min: 10, max: 30 }),check('name','Name length should be 10 to 20 characters').isLength({ min: 10, max: 20 }),check('mobile','Mobile number should contains 10 digits').isLength({ min: 10, max: 10 }),check('password','Password length should be 8 to 10 characters').isLength({ min: 8, max: 10 })], (req, res) => {// validationResult function checks whether// any occurs or not and return an objectconst errors = validationResult(req);// If some error occurs, then this// block of code will runif(!errors.isEmpty()) {res.json(errors)}// If no error occurs, then this// block of code will runelse{res.send("Successfully validated")}});app.listen(PORT,function(error) {if(error)throwerrorconsole.log("Server created Successfully on PORT ", PORT)})chevron_rightfilter_none
Steps to run the program:
- The project structure will look as shown below:

- Make sure you have a ‘view engine’. We have used “ejs” and also install express and express-validator, body-parser using following commands:
npm install ejs
npm install express
npm install body-parser
npm install express-validator
- Run index.js file using below command:
node index.js

- Open the browser and type this URL http://localhost:8080/, the fill this sample form with correct data as shown below:

- Then submit the form and if no error occurs, then you will see the following output:

- And if you try to submit the form with incorrect data, then you will see the error message as shown below:
Recommended Posts:
- How to Validate Data using hapi/joi Module in Node.js ?
- How to Validate Data using validator Module in Node.js ?
- Nodejs | Automatic restart NodeJs server with nodemon
- Encrypting Data in NodeJS
- How to Generate fake data using Faker module in Node.js ?
- How to validate an Email using PHP?
- Validate a password using HTML and JavaScript
- How to validate URL using regular expression in JavaScript?
- How to validate email address using RegExp in JavaScript ?
- How to validate an input is alphanumeric or not using JavaScript ?
- How to validate if input date (end date) in input field must be after a given date (start date) using express-validator ?
- How to validate if input in input field exactly equals to some other value using express-validator ?
- How to validate if input in input field has alphanumeric characters only using express-validator ?
- How to validate if input in input field has base64 encoded string using express-validator ?
- How to validate if input in input field has boolean value using express-validator ?
- How to validate if input in input field has ASCII characters using express-validator ?
- How to validate if input in input field has base 32 encoded string using express-validator ?
- How to validate if input in input field has alphabets only using express-validator ?
- How to validate if input in input field has BIC or Swift code only using express-validator ?
- How to validate if input in input field has integer number only using express-validator ?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

