express-validator
Express middleware for validating and sanitizing request data — chain validators on body, query, params, and headers.
express-validator
ExpressExpress middleware for validating and sanitizing request data — chain validators on body, query, params, and headers.
Fit
Bundle (gzip)
7.4 kB
27.3 kB raw
Install size includes transitive dependencies. Bundle size is gzipped browser payload.
Freshness
The Problem
Validating incoming request data in Express requires manually checking every field, accumulating errors, and returning consistent error responses. Sanitizing inputs (trimming whitespace, escaping HTML) is often forgotten and leads to security vulnerabilities.
What It Does
express-validator provides body(), param(), query(), and header() validators that chain validation rules (isEmail(), isLength(), notEmpty()) and sanitizers (trim(), escape()). Call validationResult(req) in your handler to collect all errors in one pass.
Installation
npm install express-validatorUsage Example
import { body, validationResult } from 'express-validator';
const validateUser = [
body('email').isEmail().normalizeEmail(),
body('password').isLength({ min: 8 }).withMessage('Password must be at least 8 characters'),
body('name').notEmpty().trim().escape(),
];
app.post('/users', validateUser, (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
// req.body is now validated and sanitized
createUser(req.body);
});Related packages
Node.js body parsing middleware — populate `req.body` from JSON, urlencoded, text, and raw payloads.
compressionExpressHTTP response compression middleware for Express — gzip/deflate responses to reduce bandwidth and improve load times.
cookie-parserExpressCookie parsing middleware for Express — parse Cookie headers into `req.cookies` and support signed cookies for tamper detection.
corsExpressCORS middleware for Express — configure cross-origin resource sharing with a single line of code.
express-async-errorsExpressSimplify Express error handling by automatically passing thrown errors to `next()`.