In this Tutorial :-

In this tutorial, we will explore how to validate HTTP requests in an Express.js application using the popular express-validator library. Proper request validation ensures data integrity, security, and a seamless user experience.
We’ll cover the installation process, validation rules, error handling, and best practices to create robust and reliable request validation in your Express.js projects.
Introduction to express-validator
Express-validator is a middleware library for request validation in Express.js applications. It provides an easy-to-use and robust way to validate incoming request data, such as request bodies, query parameters, and route parameters. Express-validator simplifies the process of validating and sanitizing user input, ensuring the data meets specific criteria and is safe to use.
The library offers a wide range of validation and sanitization functions, including built-in validation rules for common use cases, such as checking for required fields, email formats, URL formats, and numeric values. It also allows developers to define custom validation rules tailored to their specific application requirements.
Express-validator integrates seamlessly with Express.js and leverages its middleware architecture. It can be easily added to Express.js applications as middleware, allowing developers to define validation rules for different routes and endpoints.
When a request is received, express-validator automatically performs the specified validation checks on the incoming data and provides detailed error messages if any validation fails.
Let’s start.
Setting Up the Project
To get started, follow these steps:
Step 1: Create a new directory for your project.
mkdir rest-api-tutorial
cd rest-api-tutorial
Step 2: Initialize a new Node.js project and install Express.
npm init -y
npm install express
Step 3: Create an index.js file in the project directory and open it in your code editor with this code.
const express = require('express');
const app = express();
const port = 3000;
// Start the server
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});
4. Install and Import the Required Middleware: Ensure that you have installed the body-parser middleware package. You can install it by running npm install body-parser. Then, import it into your Express application:
const bodyParser = require('body-parser')
Use the Middleware in Your Application: Add the following lines of code to your Express application to use the body-parser middleware:
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
The body-parser middleware is used to parse different types of request bodies, such as URL-encoded and JSON bodies.
Installation and Setup
To get started, install the express-validator library by running the following command:
npm install express-validator
Next, in your Express.js application, import the necessary dependencies:
const express = require('express');
const { body, validationResult } = require('express-validator');
Basic Request Validation
Let’s start with validating the request body. Suppose we have an API endpoint to create a user. Add the following route handler to your Express application:
app.post('/users', [
body('name').notEmpty().withMessage('Name is required'),
body('email').isEmail().withMessage('Invalid email'),
body('passcode').isLength({ min: 6 }).withMessage('Password must be at least 6 characters long'),
], (req, res) => {
// Handle the request
});
In the above code, we use the body function from express-validator to specify validation rules for each field in the request body. The notEmpty rule ensures the field is not empty, the isEmail rule checks for a valid email format, and the isLength rule validates the minimum length of the password.
Please note that, adding validation checks for a particular field is not enough, you have to also add following code in your function logic to bring it in action.
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
For your convenience, here’s the complete code of app.js
const express = require('express');
const bodyParser = require('body-parser');
const { body, validationResult } = require('express-validator');
const app = express();
const port = 3000;
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
let users = [];
app.post('/users', [
body('name').notEmpty().withMessage('Name is required'),
body('email').isEmail().withMessage('Invalid email'),
body('passcode').isLength({ min: 6 }).withMessage('Passcode must be at least 6 characters long'),
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
users.push(req.body);
res.send({
message: "User Added",
body: req.body
});
});
// Start the server
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});
Now, run your application with node index.js command and hit [POST] http://localhost:3000/users on Postman with given request body (where we are violating all 3 rules).
Request Body -:
{
“id”: 2,
“email”: “shrey@com”,
“passcode”: “1111”
}

Next, let’s validate query parameters. Suppose we have an API endpoint to retrieve a user by their ID. Add the following route handler:
app.get('/users/:id', [
param('id').isInt().withMessage('Invalid user ID'),
], (req, res) => {
// Handle the request
});
In this example, we use the param function to validate the id parameter in the URL. The isInt rule ensures that the parameter value is an integer.

Similarly, you can validate route parameters using the param function.
Custom Validation Rules
You can define custom validation rules based on your specific requirements. For example, let’s create a custom rule to validate that a username is unique:
const isUsernameUnique = (value) => {
// Perform a check against your database or data source
// Return a Promise that resolves with a boolean value
};
app.post('/users', [
body('username').custom(isUsernameUnique).withMessage('Username is already taken'),
], (req, res) => {
// Handle the request
});
Chaining Validation Rules
You can chain multiple validation rules for a field. For example, let’s validate that a password contains both letters and numbers:
app.post('/users', [
body('password')
.matches(/[a-zA-Z]/).withMessage('Password must contain at least one letter')
.matches(/[0-9]/).withMessage('Password must contain at least one number'),
], (req, res) => {
// Handle the request
});
Sanitization and Data Transformation
express-validator also provides sanitization methods to clean and transform input data. For instance, you can sanitize and trim input values:
app.post('/users', [
body('email').isEmail().normalizeEmail(),
body('username').trim(),
], (req, res) => {
// Handle the request
});
Custom Error Messages: You can customize error messages for validation rules. For example:
app.post('/users', [
body('email').isEmail().withMessage('Please provide a valid email address'),
], (req, res) => {
// Handle the request
});
express-validator Methods
Express-validator provides several methods for validating and sanitizing request data. Here are some of the commonly used methods:
check(field [, message]): Checks the value of the specified field against validation rules.
body(field [, message]): Alias for check method, specifically used for validating request body parameters.
param(field [, message]): Alias for check method, specifically used for validating route parameters.
query(field [, message]): Alias for check method, specifically used for validating query parameters.
header(field [, message]): Alias for check method, specifically used for validating request headers.
validationResult(req): Extracts the validation errors from the request and returns a Result object.
sanitize(field): Sanitizes the value of the specified field.
sanitizeBody(field): Alias for sanitize method, specifically used for sanitizing request body parameters.
sanitizeParam(field): Alias for sanitize method, specifically used for sanitizing route parameters.
sanitizeQuery(field): Alias for sanitize method, specifically used for sanitizing query parameters.
sanitizeHeader(field): Alias for sanitize method, specifically used for sanitizing request headers.
oneOf(validators [, message]): Validates the value against multiple validators, where at least one of them must pass.
custom(validator [, message]): Allows defining custom validation logic using a callback function.
withMessage(message): Specifies a custom error message for a validation rule.
isString(): Checks if the value is a string.
isBoolean(): Checks if the value is a boolean.
isNumeric(): Checks if the value is a numeric string.
isInt(options): Checks if the value is an integer, optionally specifying additional options such as minimum and maximum values.
isFloat(options): Checks if the value is a floating-point number, optionally specifying additional options such as minimum and maximum values.
isEmail(options): Checks if the value is a valid email address, optionally specifying additional options such as domain whitelist.
isURL(options): Checks if the value is a valid URL, optionally specifying additional options such as allowed protocols.
isLength(options): Checks if the value’s length falls within the specified range, optionally specifying minimum and maximum lengths.
isIn(values): Checks if the value is present in the specified array of allowed values.
isMobilePhone(locale): Checks if the value is a valid phone number for the specified locale.
matches(pattern [, modifiers]): Checks if the value matches the specified regular expression pattern.
toDate(): Converts the value to a JavaScript Date object.
escape(): Escapes special characters in the value.
trim(): Trims leading and trailing whitespace from the value.
These are just a few examples of the methods available in express-validator. The library offers many more methods and options to cater to various validation and sanitization requirements. The choice of which methods to use depends on the specific needs of your application and the data you need to validate.
In this tutorial, we covered the basics of validating HTTP requests using express-validator. You learned how to perform basic and advanced request validation, handle errors, and apply best practices. With express-validator, you can create reliable and secure Express.js APIs.
Google Search Terms:
Express-validator tutorial, Validating HTTP requests in Express with express-validator, Express.js request validation with express-validator, Express-validator examples for request validation, How to use express-validator for request validation, Handling request validation in Express using express-validator, Express.js form validation with express-validator, Express.js API input validation with express-validator, Server-side input validation in Express with express-validator, Express.js request validation best practices, Express.js form validation middleware,Express.js validation middleware with express-validator, Custom validation rules in express-validator, Handling validation errors in Express using express-validator,
Express.js request validation using middleware and express-validator, Validating request body in Express with express-validator, Input sanitization in Express using express-validator, Validating query parameters in Express with express-validator, Request validation error handling in Express with express-validator,
Express.js input validation middleware for REST APIs,
