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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-12 17:27:02645browse

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(); 
    }
];

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');
});

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(); 
    }
];

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');
});

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();
    }
];

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:
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