Express middleware for the validator module.
express-validator is a middleware layer for Express.js applications that provides request validation and sanitization capabilities by wrapping the popular validator.js library. It allows developers to validate incoming data from request bodies, query parameters, route params, headers, and cookies using a fluent chaining API or schema-based definitions. With over 1.2 million weekly downloads, it has become a standard solution for input validation in Express applications.
The package exists to solve a critical problem in web applications: ensuring that user input meets expected formats and constraints before it reaches business logic or database layers. Without proper validation, applications are vulnerable to invalid data states, security issues like XSS attacks, and unpredictable runtime errors. express-validator provides both validation rules (checking if data meets criteria) and sanitization functions (cleaning data to remove potentially harmful content).
The library is used across production applications ranging from small REST APIs to large-scale enterprise systems. Its integration as native Express middleware means minimal configuration overhead, and its 100+ built-in validators cover common scenarios like email validation, length checks, date formats, and numeric ranges. The package maintains compatibility with Express 4.x and later, requiring Node.js 14 or higher in version 7.x.
Developers choose express-validator for its balance between simplicity and power. The chaining syntax reads naturally and integrates directly into route handlers, while the error reporting system provides structured feedback that can be easily transformed into API responses. It handles the repetitive work of input validation so developers can focus on application logic rather than writing custom validation code for every endpoint.
const express = require('express');
const { body, query, validationResult } = require('express-validator');
const app = express();
app.use(express.json());
app.post('/api/users',
body('email').isEmail().normalizeEmail(),
body('password').isLength({ min: 8 }).matches(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])/),
body('age').optional().isInt({ min: 18, max: 120 }),
body('username').trim().escape().isLength({ min: 3, max: 20 }),
body('confirmPassword').custom((value, { req }) => {
if (value !== req.body.password) {
throw new Error('Passwords do not match');
}
return true;
}),
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
res.json({ message: 'User created', data: req.body });
}
);
app.get('/api/posts',
query('page').optional().isInt({ min: 1 }).toInt(),
query('limit').optional().isInt({ min: 1, max: 100 }).toInt(),
query('category').optional().isIn(['tech', 'news', 'sports']),
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
const { page = 1, limit = 10, category } = req.query;
res.json({ page, limit, category, posts: [] });
}
);
app.listen(3000);User Registration Forms: Validate that email addresses are properly formatted, passwords meet complexity requirements, and username lengths fall within acceptable ranges. Sanitize text inputs to prevent XSS attacks by escaping HTML characters before storing user profiles in databases.
API Parameter Validation: Ensure query parameters for pagination, filtering, or search endpoints contain valid data types and ranges. For example, verify that page numbers are positive integers, dates follow ISO format, and enum values match allowed options before executing database queries.
File Upload Metadata Validation: Validate file size limits, allowed MIME types, and filename sanitization when processing multipart form data. Check that associated metadata like descriptions or tags meet length and format requirements before accepting uploads.
Authentication Endpoints: Validate login credentials, ensuring email/username fields are non-empty and properly formatted, and that token strings in headers match expected patterns. Sanitize inputs to prevent SQL injection attempts through authentication forms.
Dynamic Search and Filter APIs: Validate complex query strings with multiple optional parameters, ensuring numeric filters are valid numbers, text searches don't contain script tags, and sort parameters match allowed column names. Transform and sanitize inputs before building database queries or search indexes.
npm install express-validatorpnpm add express-validatorbun add express-validator