• Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements
CODE OF GEEKS

We at CODE OF GEEKS, aim at providing best and quality content for our users at no extra cost.

    • Study Materials
      • InfyTQ Archive
      • Infosys Archive
      • TCS Archive
      • Accenture Archive
      • AMCAT Archive
      • Capgemini Archive
      • Cisco Archive
      • CoCubes Archive
      • Cognizant(CTS) Archive
      • Deloitte Archive
      • DXC Archive
      • Goldman Sachs Archive
      • Hexaware Technologies Archive
      • LTI Archive
      • MindTree Archive
      • Virtusa Archive
      • Wipro Archive
    • Interview Preparation
      • C Interview Questions
      • Data Structures Interview Questions
      • DBMS Interview Questions
      • HR Interview Questions
      • Java Interview Questions
      • Operating System Interview Questions
      • Python Interview Questions
      • SQL Query Interview Questions
    • Tutorials
      • Node.js Tutorial
      • Express.js Tutorial
      • Python Tutorial
    • Programming
      • C Programming MCQs
      • C Code Snippets – Output Questions
      • Python Code Snippets – Output Questions
      • Java Code Snippets – Output Questions
    • Aptitude
      • Verbal Ability for Placements
CODE OF GEEKS
CODE OF GEEKS
  • Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements

Validating HTTP Requests using express-validator: A Comprehensive Tutorial

  • July 1, 2023
  • CODE OF GEEKS
  • 0
In this Tutorial :-
  • Introduction to express-validator
  • Setting Up the Project
  • Installation and Setup
  • Basic Request Validation
  • Custom Validation Rules
  • Chaining Validation Rules
  • Sanitization and Data Transformation
  • express-validator Methods
Validating HTTP Requests using express-validator
Validating HTTP Requests using express-validator

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”
}

API returning 400
API returning 400

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.

Got Validation Error as string value is not allowed
Got Validation Error as string value is not allowed

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,

Tags: Custom validation rules in express-validatorExpress-validator examples for request validationExpress-validator tutorialExpress.js API input validation with express-validatorExpress.js form validation middlewareExpress.js form validation with express-validatorExpress.js input validation middleware for REST APIsExpress.js request validation best practicesExpress.js request validation using middleware and express-validatorExpress.js request validation with express-validatorExpress.js validation middleware with express-validatorHandling request validation in Express using express-validatorHandling validation errors in Express using express-validatorHow to use express-validator for request validationInput sanitization in Express using express-validatorRequest validation error handling in Express with express-validatorServer-side input validation in Express with express-validatorValidating HTTP requests in Express with express-validatorValidating query parameters in Express with express-validatorValidating request body in Express with express-validator
  • Previous Session Handling in Express: A Step-by-Step Tutorial
  • Next Building a REST API with Express: A Step-by-Step Tutorial

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Advertise with us

More on Node.js

  • Introduction to Node.js
  • NPM in Node.js
  • Non-Blocking Nature of Node.js
  • First Application with Node.js
  • Node.JS Modules
  • HTTP Module Node.js
  • Reading File with Node.js
  • Writing File with Node.js
  • Creating File with Node.js
  • Updating File with Node.js
  • Deleting File with Node.js
  • Renaming File with Node.js
  • URL Module in Node.js
  • Event Programming with Node.js
  • async-await in Node.js
  • Buffer in Node.js
  • Sending Mails with Node.js
  • Connecting to MySQL(CRUD) in Node.js

More on Express.js

  • Introduction to Express.js
  • Creating First App with Express.js
  • Routes in Express.js
  • Middlewares in Express.js
  • Web App with Express & Pug
  • Web App with Express & EJS
  • Serving Static Files with Express.js
  • Handling Forms with Express.js
  • Handling File uploads in forms
  • Working with Cookies in Express.js
  • Session Handling with Express.js
  • REST API with Express.js
  • Validating Requests in Express.js
  • Fetch data from External API with axios
CODE OF GEEKS

Subscribe to Newsletter

CODE OF GEEKS

Learn | Code | Achieve

Reach us

[email protected]
We at CODE OF GEEKS, aim at providing quality content to our users at no cost.
CODE OF GEEKS

Important Pages

About us
Advertise
Privacy Policy
Terms and Conditions
Refund Policy
Contact us

Placements – Study Materials

TCS NQT     Wipro     CapGemini
Accenture     MindTree     CTS
DXC     Hexaware Technologies     AMCAT
CoCubes     Goldman Sachs     Dell
Cisco     Deloitte     Virtusa     LTI     Infosys   

Tutorials

Python
Node.js
Express.js
Golang

Recent Posts

Strings in Go and its basic operations
  • August 11, 2023
Introduction to Functions in Go programming
  • August 11, 2023

Copyright @ CODE OF GEEKS. All Rights Reserved.