Home > Article > Web Front-end > 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
You can either use body() or check() to setup the validation rules.
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(); } ];
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'); });
Now, any requests to /register will be validated according to the rules in validateRegistration before the registration logic executes.
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.
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.
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
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.
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!