Skip to content
Related Articles

Related Articles

How to Validate Data using express-validator Module in Node.js ?
  • Difficulty Level : Expert
  • Last Updated : 29 Apr, 2020
GeeksforGeeks - Summer Carnival Banner

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:

  1. You can install this package by using this command.
    npm install express-validator
  2. After installation, you can check your express-validator module version in command prompt using the command.
    npm version express-validator
  3. After that, you can just create a simple data as shown below to send the data to the server.

    Filename: SampleForm.ejs

    <!DOCTYPE html>
            <title>Validation using Express-Validator</title>
    <h1>Demo Form</h1>
    <form action="saveData" method="POST">
          Enter your Email    : <input type="text" name="email"> <br>
          Enter your Name     : <input type="text" name="name"> <br>
          Enter your Number   : <input type="number" name="mobile"> <br>
          Enter your Password : <input type="password" name="password"> <br>
          <input type="submit" value="Submit Form"
  4. 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()
    var PORT = process.env.port || 3000
    // View Engine Setup
    app.set("views", path.join(__dirname))
    app.set("view engine", "ejs")
    // Body-parser middleware
    app.use(bodyparser.urlencoded({ extended: false }))
    app.get("/", function (req, res) {
    // check() is a middleware used to validate
    // the incomming data as per the fields'/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 object
        const errors = validationResult(req);
        // If some error occurs, then this
        // block of code will run
        if (!errors.isEmpty()) {
        // If no error occurs, then this
        // block of code will run
        else {
            res.send("Successfully validated")
    app.listen(PORT, function (error) {
        if (error) throw error
        console.log("Server created Successfully on PORT ", PORT)

Steps to run the program:

  1. The project structure will look as shown below:
    project structure
  2. 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
  3. Run index.js file using below command:
    node index.js

    Output of node index.js

  4. Open the browser and type this URL http://localhost:8080/, the fill this sample form with correct data as shown below:
  5. Then submit the form and if no error occurs, then you will see the following output:
    success output
  6. And if you try to submit the form with incorrect data, then you will see the error message as shown below:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :