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 check
and 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
, andreq.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()
orbody()
. -
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()
- Scope: General-purpose validator.
-
Validation Areas: Can check for data across multiple request parts (such as
req.body
,req.query
,req.params
). - 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 } 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();
}
];
Here, check('email')
will look for the email field in all parts of the request, including req.body
, req.query
, and req.params
.
- body()
- Scope: Specifically targets req.body.
- 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).
- 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 { body } from 'express-validator';
const validateBodyEmail = [
body('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();
}
];
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, body, validationResult } from 'express-validator';
app.post('/submit-form', [
body('email').isEmail().withMessage('Please provide a valid email'),
check('token').notEmpty().withMessage('Token is required')
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
// YOUR ROUTE LOGIC
});
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.
Top comments (0)