AppDividend
Latest Code Tutorials

Express Form Validation Example From Scratch

Form Validation in Node js

1,457

Express Form Validation Example From Scratch. In this tutorial, we will use express-validator package to validate the input request. We will create a form and send the POST request to the server and then if the request fails against the validation, then it will respond with an error message. If you are beginner in Node.js then check out my Node js Express Tutorial For Beginners From Scratch 2018

Express Form Validation Example

We install the package called 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 install express and express-validator package.

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 to 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. nodemon package automatic restarts the server when we change into a server.js file, and we do not manually restart the server, which is great and saves you a lot of time. Also, add the start property in the package.json file.

 "start": "nodemon server.js"

So 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 project folder root. Inside views folder, create 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.use(express.static('public'));

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

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

Step 4: Configure express-validator module.

Install the body-parser and other dependencies via npm.

npm install body-parser express-session cookie-parser --save

body-parser: Parses the incoming request data.

express-session: This module uses to store the session data like error and success message.

Related Posts
1 of 10
// 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(expressValidator());
app.use(cookieParser());
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 call blockchain.hbs

<!-- blockchain.hbs -->

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

Okay, 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 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){
   res.render('blockchain');
});

module.exports = router;

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

// server.js

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

app.use('/blockchain',blockchain);

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

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

   var errors = req.validationErrors();
   if(errors){
      req.session.errors = errors;
      req.session.success = false;
      res.redirect('/blockchain');
   }
   else{
      req.session.success = true;
      res.redirect('/');
   }
});

Here, 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, then all the validation errors are stored in the errors variable. If errors variable is not empty, then it will redirect us to form page with the errors. Else redirect to the home route. Also, define the form action. We need to give this post route so that we can catch the submitted values.

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

If you submit the form without any values, then it will redirect back with the errors. 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 need to 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 container class to display the errors.

<!-- blockchain.hbs  -->

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

We have used handlebars, so its syntax is like above. If there are errors, then we can access its property msg, which has all of our validation messages. The express-validator function will set the msg property for us. We just need to put that errors object into a session and then display it on the frontend.

 

express validation tutorial

If all the values are correct, then it will redirect to a home route.

So that’s it for Express Form Validation Tutorial Example From Scratch.

 

1 Comment
  1. Jan Kuchar says

    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?

Leave A Reply

Your email address will not be published.