Home Web Front-end JS Tutorial How to use express-validator as a middleware in Express App

How to use express-validator as a middleware in Express App

Nov 12, 2024 pm 05:27 PM

How to use express-validator as a middleware in Express App

Hello everyone, In this article we will learn how can we setup the express-validator as a middleware, also we will deep dive in details about the proper use case of checkand body methods in express-validator.
express-validator is a powerful library for validating and sanitizing inputs in Express applications. It provides a robust set of validation and sanitization functions that can be used to ensure incoming data meets specific requirements. This documentation will guide you through setting up validation middleware and illustrate the key differences between the check and body methods for validation.

After installing the express-validator, follow the below steps

Setting Up Validation Rules

You can either use body() or check() to setup the validation rules.

  • check(): A flexible validator that can check data across various parts of a request (such as req.body, req.query, and req.params).
  • body(): A more targeted validator that focuses specifically on validating data within req.body.
  • validationResult(): To retrieve and handle validation results in a middleware function.

Defining Validation Middleware

To make your validation reusable and keep your routes clean, define validation rules in a middleware function. Here’s an example middleware function for a user registration route that checks the email and password fields.

import { check, validationResult } from 'express-validator';

// DEFINE VALIDATION RULES
const validateRegistration = [
    check('email')
        .isEmail()
        .withMessage('Please enter a valid email address')
        .isLength({ max: 100 })
        .withMessage('Email cannot exceed 100 characters'),

    check('password')
        .isLength({ min: 6 })
        .withMessage('Password must be at least 6 characters long')
        .isLength({ max: 255 })
        .withMessage('Password cannot exceed 255 characters'),

    // CHECK FOR VALIDATION ERRORS
    (req, res, next) => {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }
        // IF NO ERRORS, MOVE TO NEXT MIDDLEWARE
        next(); 
    }
];
Copy after login
Copy after login

Using Middleware in Routes

After defining your validation middleware, use it in the route that handles the incoming request. This keeps validation separate from the route logic.

import express from 'express';
const app = express();

app.use(express.json());

app.post('/register', validateRegistration, (req, res) => {
    // USE YOUR REGISTRATIO LOGIC HERE
    res.status(201).json({ message: 'User registered successfully' });
});

app.listen(3000, () => {
    console.log('Server running on http://localhost:8080');
});
Copy after login
Copy after login

How It Works

  • Define validation rules: Specify each field’s validation requirements (such as length and format) using check() or body().
  • Check for errors: Use validationResult() to determine if any validation errors exist. If errors are found, they’re returned to the client with a 400 status code.
  • Continue: If no errors are found, next() is called to proceed with the route handler logic or to the next middleware.

Now, any requests to /register will be validated according to the rules in validateRegistration before the registration logic executes.

Detailed Comparison: check vs body

Both check() and body() are functions within express-validator that define validation rules for incoming data. However, they differ in where they look for data within the request and how they’re typically used.

  • check()
  1. Scope: General-purpose validator.
  2. Validation Areas: Can check for data across multiple request parts (such as req.body, req.query, req.params).
  3. Typical Use Cases: Useful when you need flexibility, such as when a field might be present in the URL, query string, or body depending on the request.

Example Usage of check()

import { check, validationResult } from 'express-validator';

// DEFINE VALIDATION RULES
const validateRegistration = [
    check('email')
        .isEmail()
        .withMessage('Please enter a valid email address')
        .isLength({ max: 100 })
        .withMessage('Email cannot exceed 100 characters'),

    check('password')
        .isLength({ min: 6 })
        .withMessage('Password must be at least 6 characters long')
        .isLength({ max: 255 })
        .withMessage('Password cannot exceed 255 characters'),

    // CHECK FOR VALIDATION ERRORS
    (req, res, next) => {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }
        // IF NO ERRORS, MOVE TO NEXT MIDDLEWARE
        next(); 
    }
];
Copy after login
Copy after login

Here, check('email') will look for the email field in all parts of the request, including req.body, req.query, and req.params.

  • body()
  1. Scope: Specifically targets req.body.
  2. Validation Area: Looks only at the request body, making it ideal for requests that carry data within the body (such as POST, PUT, or PATCH requests).
  3. Typical Use Cases: Preferred when handling form submissions or JSON payloads, where you know the data will only be in the request body.

Example Usage of body()

import express from 'express';
const app = express();

app.use(express.json());

app.post('/register', validateRegistration, (req, res) => {
    // USE YOUR REGISTRATIO LOGIC HERE
    res.status(201).json({ message: 'User registered successfully' });
});

app.listen(3000, () => {
    console.log('Server running on http://localhost:8080');
});
Copy after login
Copy after login

Here, body('email') will only check for the email field within req.body, so it won’t detect it if it’s in req.query or req.params.

When to Use Each

  • check(): When the data location may vary, such as in a URL parameter, query string, or body.
  • body(): When you’re only interested in validating data in req.body, which is common for APIs that accept form data or JSON payloads.

Example with Both
You can use both check() and body() in the same validation array to handle data from different parts of the request.

import { check } from 'express-validator';

const validateEmail = [
    check('email')
        .isEmail()
        .withMessage('Invalid email address'),

    (req, res, next) => {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }
        next();
    }
];

Copy after login

In this example:
body('email') only validates email in the request body.
check('token') searches for token across req.body, req.query, and req.params.

Conclusion

Using express-validator in this way keeps validation clean, manageable, and flexible enough to handle a variety of input formats and sources, helping ensure data integrity and security in your application.

The above is the detailed content of How to use express-validator as a middleware in Express App. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles