How to Implement Form Validation in Node.js and Express Using Express-Validator

How to Implement Form Validation in Node.js and Express Using Express-Validator

Handling user input safely is one of the most critical responsibilities of backend development. Accepting unvalidated data can lead to corrupted databases, broken application states, and severe security vulnerabilities like injection attacks.

In this tutorial, we will walk through how to build robust form validation in a Node.js application using Express, EJS, Body-Parser, and the express-validator library.

Prerequisites & Tech Stack

Make sure you have Node.js installed on your system. We will be using the following packages:

  • Express: Fast, unopinionated web framework for building Node.js applications.
  • Body-Parser: Middleware to extract incoming request data and expose it on req.body.
  • Path: Built-in Node.js module for working with file and directory paths.
  • Express-Validator: A set of Express middleware wrappers for the validator.js library used to validate and sanitize input fields.
  • EJS: Embedded JavaScript templating engine for dynamic views.

Step 1: Set Up the Project Folder

Open your terminal or command prompt and run the following commands to create and enter your project directory:

mkdir validations
cd validations

Initialize your workspace. This creates a package.json configuration file, which tracks your project's metadata and dependencies:

npm init -y

Step 2: Install Required Packages

Install Express, EJS, Body-Parser, and Express-Validator in a single command:

npm install express ejs body-parser express-validator

Step 3: Configure Project Scripts

Open your newly created package.json file and add a "start" script under the "scripts" configuration block so you can run your app cleanly:

"scripts": {
  "start": "node app.js"
}

Next, create your application entry point file named app.js in the root directory, along with a views folder containing a register.ejs file.

Step 4: Write the Express Server and Validation Logic (app.js)

Create app.js and add the following code. This script sets up Express, handles route mapping, and applies express-validator rules for name, email, and phno fields.

var express = require('express')
var bodyParser = require('body-parser')
var path = require('path')
var {check, validationResult} = require('express-validator')

var app = express();

app.set("views", path.resolve(__dirname, 'views'))
app.set('view engine', 'ejs')

app.use(bodyParser.urlencoded({extended: false}))

app.get('/', (req, res) => {
    res.render('register', {data: {}})
})

app.post('/', 
    check('name').isLength({min: 5}).withMessage("enter name ").isAlpha().withMessage('name should have alphabets only'),
    check('email').isEmail().withMessage('enter valid email'),
    check('phno').isMobilePhone().withMessage('enter correct number'),
    (req, res) => {
        var err = validationResult(req);
        if(!err.isEmpty()){
            res.render('register', {data: err.array()})
        } else {
            res.redirect('/')
        }
    }
)

var port = process.env.PORT || 3000;
app.listen(port, () => console.log(`server is running at ${port}`))

module.exports = app;

Code Breakdown:

  • path.resolve(__dirname, 'views'): Tells Express exactly where your views directory is located.
  • app.set('view engine', 'ejs'): Instructs Express to render any file ending in .ejs using the EJS template engine.
  • check(): Analyzes specific incoming request fields and attaches validation rules (such as minimum length, alphabetic constraint, email structure, or phone number compliance).
  • validationResult(req): Collects any validation errors identified by check() and formats them into an accessible array via err.array().

Step 5: Create the View Template (views/register.ejs)

Create a folder named views, and inside it, create a file named register.ejs. This template checks for validation errors passed from the server and displays them dynamically in a loop above the registration form.

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Node.js Form Validation Tutorial</title>
</head>
<body>
    <% if(data.length > 0) {%>
        <% for(var i=0; i < data.length; i++){%>
            <div style="color: red;">
                <%= data[i].msg%>
            </div>
        <%}%>
    <% } %>
    
    <form action="/" method="POST">
        <input type="text" name="name" placeholder="enter the name"><br><br>
        <input type="text" name="email" placeholder="enter email"><br><br>
        <input type="text" name="phno" placeholder="enter phno"><br><br>
        <input type="submit" value="register"><br>
    </form>
</body>
</html>

Step 6: Run and Test Your Application

  • Start your server in your terminal:
    npm start
  • Open your web browser and navigate to:
    http://localhost:3000

Comments

Popular posts from this blog

How to Setup a Flask Project in Python: Step-by-Step Guide

How to Hash Passwords in Node.js Using Bcryptjs, Express and Mongoose

How to Upload Images in Node.js and Express Using AJAX and jQuery