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

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

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <!DOCTYPE html>
    <html>
        <head>
            <title>Validation using Express-Validator</title>
        </head>
    <body>
    <h1>Demo Form</h1>
       
    <form action="saveData" method="POST">
      <pre>
          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"
      </pre>
    </form>
       
    </body>
    </html>

    chevron_right

    
    

  4. After that, you can just create a file, for example index.js as show below:

    Filename: index.js

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    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.use(bodyparser.json())
      
    app.get("/", function (req, res) {
        res.render("SampleForm");
    })
      
    // check() is a middleware used to validate
    // the incomming data as per the fields
    app.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 object
        const errors = validationResult(req);
      
        // If some error occurs, then this
        // block of code will run
        if (!errors.isEmpty()) {
            res.json(errors)
        }
      
        // 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)
    })

    chevron_right

    
    

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:
    Signup.ejs
  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:
    error-message



My Personal Notes arrow_drop_up

Recommended Posts:


To obtain a position of responsibility that utilizes my skills and keen to work in an environment where I can enrich my knowledge

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.