Paramclasses Academy - Blog

Tutorials Details

←
Post 22 of 40
→

Request Validation in Express.js Using Popular Validation Libraries

Request Validation in Express.js Using Popular Validation Libraries

October 30, 2026

✦ Request Validation in Express.js Using Popular Validation Libraries

❖ Introduction

When building a web application or REST API with Node.js and Express.js, validating incoming data is an essential part of backend development. Users may submit empty fields, invalid email addresses, incorrect mobile numbers, or unexpected values. If an application accepts this data without checking it, it can cause errors and unreliable results.

For example, a student registration API should not accept an empty student name or a missing course. Similarly, a signup API should check whether the email address has a valid format.

Request validation means checking incoming request data before processing it or saving it to a database.

In this tutorial, we will learn how to validate request bodies, route parameters, and query parameters using popular validation libraries, especially express-validator. We will also build a practical Student Registration API with validation and proper error responses.

✦ What Is Request Validation in Express.js?

Request validation checks whether the data submitted by a client meets the application's requirements.

Suppose a registration form submits the following JSON:

{
    "name": "",
    "email": "invalid-email",
    "age": -5
}

This data contains several problems:

  • The name is empty.

  • The email address has an invalid format.

  • The age is negative.

A validation system can detect these issues and return a 400 Bad Request response instead of processing invalid data.

Validation is useful for:

  • Student registration forms

  • Login and signup APIs

  • Contact forms

  • E-commerce checkout

  • Product management

  • Database CRUD operations

  • Search and filtering endpoints

Remember that validation helps improve data quality, but it does not replace authentication, authorization, or database security.

✦ Popular Validation Libraries for Node.js

Several libraries can help validate requests in Express.js.

Library Main Purpose
express-validator Validate and sanitize Express request data using validation chains
Joi Define schemas that describe acceptable data
Zod Validate data using schemas with strong JavaScript and TypeScript support
Ajv Validate data against JSON Schema definitions

 

 

For beginners working with Express.js, express-validator is a useful starting point because its validation rules integrate directly with routes and middleware.

In this tutorial, we will use express-validator.

✦ Step 1: Create a Node.js Project

First, make sure Node.js and npm are installed on your computer.

Open the terminal and run:

mkdir express-validation
cd express-validation
npm init -y
npm install express express-validator

Create a file named app.js.

Your project structure will look like this:

express-validation/
├── node_modules/
├── app.js
├── package.json
└── package-lock.json

We will use Express.js to create the server and express-validator to define and check validation rules.

✦ Step 2: Create Your First Validation Rule

Let's start with a simple example that validates a student's name.

const express = require("express");
const { body, validationResult } = require("express-validator");

const app = express();

app.use(express.json());

app.post(
    "/students",
    body("name")
        .trim()
        .notEmpty()
        .withMessage("Student name is required"),

    (req, res) => {
        const errors = validationResult(req);

        if (!errors.isEmpty()) {
            return res.status(400).json({
                success: false,
                errors: errors.array()
            });
        }

        res.status(201).json({
            success: true,
            message: "Student name validated",
            name: req.body.name
        });
    }
);

app.listen(3000, () => {
    console.log("Server running at http://localhost:3000");
});

Run the application:

node app.js

In Postman, select POST and enter:

http://localhost:3000/students

Choose Body → raw → JSON and submit:

{
    "name": ""
}

The API returns a 400 Bad Request response because the name is empty.

Now submit:

{
    "name": "Rahul Sharma"
}

The request passes the name validation and returns 201 Created.

The important functions are:

  • body("name") selects the request body's name field.

  • .trim() removes whitespace around a string.

  • .notEmpty() checks that the field is not empty.

  • .withMessage() defines the error message.

  • validationResult(req) collects validation errors.

✦ Step 3: Validate Multiple Fields

Real applications usually require more than one field. For example, a student registration API may need a name, email address, and course.

Replace your existing app.js with the following complete example:

const express = require("express");
const {
    body,
    validationResult
} = require("express-validator");

const app = express();
const PORT = 3000;

app.use(express.json());

app.post(
    "/api/students",

    body("name")
        .trim()
        .notEmpty()
        .withMessage("Name is required")
        .isLength({ max: 100 })
        .withMessage("Name cannot exceed 100 characters"),

    body("email")
        .trim()
        .isEmail()
        .withMessage("Enter a valid email address"),

    body("course")
        .trim()
        .notEmpty()
        .withMessage("Course is required"),

    (req, res) => {
        const errors = validationResult(req);

        if (!errors.isEmpty()) {
            return res.status(400).json({
                success: false,
                message: "Validation failed",
                errors: errors.array().map(error => ({
                    field: error.path,
                    message: error.msg
                }))
            });
        }

        const { name, email, course } = req.body;

        res.status(201).json({
            success: true,
            message: "Student data validated successfully",
            data: {
                name,
                email,
                course
            }
        });
    }
);

app.listen(PORT, () => {
    console.log(`Server running at http://localhost:${PORT}`);
});

This example validates three fields before returning a response.

Note: This API validates the submitted information but does not save it to a database. Database insertion can be added after successful validation.

✦ Step 4: Understand Validation Error Responses

Suppose the client submits:

{
    "name": "",
    "email": "wrong-email",
    "course": ""
}

The API returns a response similar to this:

{
    "success": false,
    "message": "Validation failed",
    "errors": [
        {
            "field": "name",
            "message": "Name is required"
        },
        {
            "field": "email",
            "message": "Enter a valid email address"
        },
        {
            "field": "course",
            "message": "Course is required"
        }
    ]
}

The response tells the frontend which fields failed validation.

A frontend can use these messages to display errors beside form fields instead of showing a generic failure message.

✦ Step 5: Validate Route Parameters

Route parameters are values included in the URL.

For example:

GET /api/students/25

Here, 25 is the student ID.

Use param() from express-validator to validate it.

const { param, validationResult } = require("express-validator");

app.get(
    "/api/students/:id",

    param("id")
        .isInt({ min: 1 })
        .withMessage("Student ID must be a positive integer"),

    (req, res) => {
        const errors = validationResult(req);

        if (!errors.isEmpty()) {
            return res.status(400).json({
                success: false,
                errors: errors.array()
            });
        }

        res.json({
            success: true,
            studentId: Number(req.params.id)
        });
    }
);

This example assumes the app object has already been created as in the previous setup. Add this route before app.listen().

Requests containing an ID such as /api/students/abc will fail validation.

Important: A valid ID format does not prove that a student exists. The application must also check the database or data store.

✦ Step 6: Validate Query Parameters

Query parameters are commonly used for search, filtering, and pagination.

Example URL:

GET /api/students?page=2

You can validate the page number using query().

const { query, validationResult } = require("express-validator");

app.get(
    "/api/search",

    query("page")
        .optional()
        .isInt({ min: 1 })
        .withMessage("Page must be a positive integer"),

    (req, res) => {
        const errors = validationResult(req);

        if (!errors.isEmpty()) {
            return res.status(400).json({
                success: false,
                errors: errors.array()
            });
        }

        const page = Number(req.query.page || 1);

        res.json({
            success: true,
            page
        });
    }
);

This example assumes the same Express application and imports as above, with query included in the express-validator destructuring.

The optional() rule means the page parameter may be omitted. If it is provided, it must be a positive integer.

✦ Step 7: Validate and Sanitize Data Correctly

Validation and sanitization are related but different.

  • Validation checks whether the input meets defined requirements.

  • Sanitization transforms input into a desired format.

For example:

body("email")
    .trim()
    .isEmail()
    .withMessage("Enter a valid email address");

Here, .trim() removes surrounding whitespace, while .isEmail() checks the email format.

However, sanitization does not automatically make input safe for every context. Use parameterized database queries to prevent SQL injection, escape output appropriately, and apply context-specific security controls.

Avoid blindly converting every field to a number or string. Choose validation and transformation rules that match the intended data type.

✦ Step 8: Other Validation Approaches

❖ Joi

Joi allows developers to define a schema for an entire object.

const Joi = require("joi");

const studentSchema = Joi.object({
    name: Joi.string().trim().min(2).max(100).required(),
    email: Joi.string().email().required(),
    course: Joi.string().trim().required()
});

const { error, value } = studentSchema.validate(req.body);

Install it using:

npm install joi

This snippet illustrates schema validation. Use it inside a route or validation middleware where req is available, then return an appropriate error response if error exists.

❖ Zod

Zod is another popular schema validation library.

const { z } = require("zod");

const studentSchema = z.object({
    name: z.string().trim().min(2),
    email: z.string().email(),
    course: z.string().trim().min(1)
});

Install it using:

npm install zod

Zod can be useful when you want to define reusable schemas for request data. Its safeParse() method lets you check whether data matches the schema without relying on exceptions for ordinary validation failures.

Choose one validation approach that suits your project. You usually do not need multiple validation libraries for the same fields.

✦ Best Practices for Request Validation

  • Validate all incoming data before processing it.

  • Define clear and consistent error messages.

  • Validate route parameters and query parameters as well as request bodies.

  • Set reasonable limits for string lengths and numeric values.

  • Validate file uploads separately, including file type and size.

  • Do not trust data merely because it comes from your own frontend.

  • Keep validation rules reusable for similar endpoints.

  • Use database constraints for rules such as unique email addresses.

  • Never expose passwords, access tokens, or internal errors in validation responses.

  • Test missing fields, invalid values, unexpected data types, and boundary cases.

✦ Frequently Asked Questions (FAQs)

1. What is request validation in Express.js?

Request validation checks whether incoming data meets the application's rules before it is processed.

2. Which validation library is good for beginners?

express-validator is a useful choice for beginners because it integrates directly with Express routes and middleware.

3. What is the difference between validation and sanitization?

Validation checks whether data meets requirements, while sanitization transforms data into a desired format.

4. Can request validation prevent SQL injection?

Validation can reject unexpected input, but it is not a substitute for parameterized database queries and other database security practices.

5. What status code should an API return for invalid input?

A 400 Bad Request response is commonly used for invalid request data. Some APIs use 422 Unprocessable Content for particular validation failures, provided their conventions are consistent.

✦ Conclusion

Request validation is a key part of building reliable Node.js and Express.js applications. Libraries such as express-validator, Joi, and Zod help developers check incoming data before processing it.

Start with required fields and email validation, then practise validating route parameters, query parameters, and more complex request schemas. Once validation works correctly, connect your API to MySQL or MongoDB and save only data that passes your application's rules.

Learn practical backend development with Param Classes.

←
Post 22 of 40
→