Form Data Validation in Node.js with express-validator

To create a form validation in express, use the “express-validator” package. We will create a form and send the POST request to the server, and then if the request fails against the validation, it will respond with an error message.

Here is the step-by-step guide to form data validation in Node.js with express-validator.

Step 1: Install the express-validator package.

You need to install Node.js to work with this tutorial. Type the following command for installing express and express-validator packages.

npm install --save express express-validator

It creates a node_modules folder and also generates a package.json file.

Step 2: Create a Node.js server.

Create a server.js file in a root folder. The server.js file will always first run because it creates a server for us, and we are using express, so type the following code in the server.js file.

// server.js

const express = require('express');
const app = express();
const expressValidator = require('express-validator');
const PORT = 3000;
app.listen(PORT, function(req, res){
   console.log('Server is running on PORT: ',PORT);

Now, I need one more development package called nodemon. The nodemon package automatically restarts the server when we change into a server.js file, and we do not manually restart the server, which is excellent and saves you a lot of time. Also, add the start property in the package.json file.

"start": "nodemon server.js"

Type the following command to bootstrap the Node.js server.

npm start

It starts the server; you can see it in the console.

Step 3: Install Handlebars Templating Engine.

Install handlbars templating engine.

npm install express-hbs --save

Create a public and views folder inside the project folder root. Inside the views folder, create the partials folder.

Set the templating engine for the express project. Type the following code in the server.js file.

// server.js

const hbs = require('express-hbs');
const path = require('path');


app.engine('hbs', hbs.express4({
   partialsDir: __dirname + '/views/partials'
app.set('view engine', 'hbs');
app.set('views', __dirname + '/views');

Included handlebars templating engine and defined public directory as a static directory. The public directory contains the project’s CSS and JS files. I have used Bootstrap to design the style. So need to put the bootstrap.min.css file here.

Step 4: Configure the express-validator module.

Install a body-parser and other dependencies via npm.

npm install body-parser express-session cookie-parser --save
  1. body-parser: Parses the incoming request data.
  2. express-session: This module stores the session data like error and success messages.
// server.js

const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const session = require('express-session');

app.use(bodyParser.urlencoded({ extended: false }));
app.use(session({secret: 'krunal', saveUninitialized: false, resave: false}));

We have used express-validator as a middleware function. It will help to check the input against the validation.

Step 5: Create a bootstrap form.

In the views folder, make one file called a blockchain.hbs.

<!-- blockchain.hbs -->

<html lang="en">
    <title>Add Network</title>
    <link href="/css/bootstrap.min.css" rel="stylesheet" type="text/css">
    <div class="container">
      <div class="panel panel-primary">
        <div class="panel-heading">
           Add Network
        <div class="panel-body">
          <form method="post" action="">
            <div class="form-group">
              <label class="col-md-4">Network Name</label>
              <input type="text" class="form-control" name="name"/>
            <div class="form-group">
              <label class="col-md-4">Network Bandwidth</label>
              <input type="text" class="form-control" name="bandwidth"/>
              <div class="form-group">
                <button type="submit" class="btn btn-primary">Add Network</button>

Now we need to render this file, but we have not defined the routes yet, so let us do that.

Step 6: Define Express Router for our application.

Create a routes folder in the root. In that folder, create one file called blockchain.route.js. 

// blockchain.route.js

const express = require('express');
const router =  express.Router();

router.get('/', function(req, res){

module.exports = router;

Next, import that routes into our server.js file.

// server.js

const blockchain = require('./routes/blockchain.route');


Navigate to http://localhost:3000/blockchain

It will display the bootstrap form.

Step 7: Define the validations.

First of all, we need to handle the POST request. So let us define the post route of our application.

// blockchain.route.js'/post', function(req, res) {
   let name =;
   let bandwidth = req.body.bandwidth;
   req.checkBody('name', 'Name is required').notEmpty();
   req.checkBody('bandwidth', 'Bandwidth is required').notEmpty();

   var errors = req.validationErrors();
      req.session.errors = errors;
      req.session.success = false;
      req.session.success = true;

First, it checks the name property from the request object, which should not be empty. Then it monitors bandwidth should not be empty.

If any of them fails against Validation, all the validation errors are stored in the errors variable. If the errors variable is not empty, it will redirect us to the form page with the errors. Else redirect to the home route. Also, define the form action. We need to give this post route to catch the submitted values.

<form method="post" action="/blockchain/post">

If you submit the form without any values, it will redirect back to the errors. However, till now, I have not displayed any errors. So let us do that.

Step 8: Display the errors.

First, in the blockchain.route.js file, we must alter the get request and add the following code.

// blockchain.route.js

router.get('/', function(req, res){
   res.render('blockchain', { success: req.session.success, errors: req.session.errors });
   req.session.errors = null;

In the blockchain.hbs file, write the following code after the container class to display the errors.

<!-- blockchain.hbs  -->

{{# if errors }}
    {{# each errors }}
          <p class="alert alert-danger">{{ this.msg }}</p>

We have used handlebars, so its syntax is like the above. We can access its property msg if there are errors, which has all of our validation messages. 

The express-validator function will set the msg property for us. We need to put that errors object into a session and then display it on the front.

express validation tutorial

That’s it.

4 thoughts on “Form Data Validation in Node.js with express-validator”

  1. This is straight forward and I’ve done this. I wonder if there is an easy way to make a good use of Bootstrap’s ‘is-invalid’ classes with validation errlr message right under the input. We’d need some way to identify each error and then check for that error in temllate. Is it possible with express-validator?

  2. This tutorial is really useful. It works well. and I have got the best way from these tutorials. So, Thanks for sharing the knowledge.

  3. This tutorial is really useful. It works well. and I have got the best way from these tutorials. So, Thanks for sharing the knowledge in express-validator package in node js.


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.