express-validator
express-validator is an active and widely used Express.js middleware library that provides a comprehensive suite of tools for validating and sanitizing request data. Currently at stable version 7.3.2, the library integrates directly with `validator.js`, offering a fluent API for defining validation chains for fields in the request body, query parameters, headers, or cookies. It typically releases patch and minor versions regularly, with major versions occurring less frequently (v7.0.0 was the first major update in almost four years). Key differentiators include its tight integration with Express's middleware system, robust error handling with `validationResult`, and extensive support for custom validators and sanitizers, making it a powerful solution for robust input validation in Node.js applications.
Common errors
-
TypeError: (0 , express_validator__WEBPACK_IMPORTED_MODULE_2__.check) is not a function
cause This error typically occurs in ESM projects where `express-validator` is imported using CommonJS-style `require()` or when destructuring named exports incorrectly, especially after v7.0.0 removed direct imports from subpaths like `/check`.fixEnsure you are using ES module import syntax for `express-validator`'s named exports: `import { check, validationResult } from 'express-validator';`. If using CommonJS, use `const { check, validationResult } = require('express-validator');`. -
Validation chain is not working / Not throwing errors
cause A common mistake is forgetting to call `validationResult(req)` to collect errors, or not correctly implementing the middleware chain to handle the errors before the route handler.fixAfter your validation middleware, ensure your route handler checks for errors: `const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); }`. Also ensure you return from the error handling block to prevent the handler from executing with invalid data. -
ReferenceError: require is not defined
cause This error occurs when trying to use `require()` in an ES module context (`'type': 'module'` in `package.json` or `.mjs` files) where CommonJS syntax is not supported by default.fixIn ES module contexts, use `import` statements instead of `require()`: `import { body, validationResult } from 'express-validator';`. -
VS Code / IDE does not show suggestions for validation methods (e.g., `.isEmail()`, `.isLength()`)
cause This can happen when the validation chain is incorrectly wrapped, often by placing it in an extra array when it's not needed or when the TypeScript types aren't being correctly inferred.fixEnsure the validation chain is correctly structured. For a single chain, pass it directly: `app.post('/route', body('field').isEmail(), (req, res) => { /* ... */ });`. If multiple chains, wrap them in a single array: `app.post('/route', [body('field1').notEmpty(), body('field2').isEmail()], (req, res) => { /* ... */ });`.
Warnings
- breaking Express-validator v7.0.0 increased the minimum supported Node.js version to 14+. Applications running on older Node.js versions must upgrade Node.js to use v7 and above.
- breaking With v7.0.0, deprecated APIs including import paths like `express-validator/check` and `express-validator/filter`, as well as sanitization-only middlewares (e.g., `sanitize()`, `sanitizeBody()`), were removed.
- gotcha Prior to v7.2.1, when using `#default()` or `#replace()` methods, non-primitive replacement values (like objects or arrays) were not cloned, potentially leading to unintended object reference reuse across multiple requests.
- gotcha The `isObject()` validator in `express-validator` v7.0.0 and later now defaults `options.strict` to `true`. This means arrays and `null` values will no longer pass `isObject()` validation by default.
- breaking The shape of validation errors changed in v7.0.0. Specifically, the `ValidationError` type for TypeScript users is now a discriminated union, which might require using `switch` or `if` statements to handle different error types. The `oneOf()` signature also changed.
Install
-
npm install express-validator -
yarn add express-validator -
pnpm add express-validator
Imports
- check
const { check } = require('express-validator/check');import { check } from 'express-validator'; - body
import * as expressValidator from 'express-validator'; const body = expressValidator.body;
import { body } from 'express-validator'; - validationResult
import validationResult from 'express-validator/validationResult';
import { validationResult } from 'express-validator'; - checkSchema
import { checkSchema } from 'express-validator';
Quickstart
import express from 'express';
import { body, validationResult } from 'express-validator';
const app = express();
app.use(express.json()); // Middleware to parse JSON bodies
app.post('/register',
body('username').notEmpty().withMessage('Username is required').trim().escape(),
body('email').isEmail().withMessage('Must be a valid email address').normalizeEmail(),
body('password').isLength({ min: 6 }).withMessage('Password must be at least 6 characters long'),
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
// If validation passes, process the registration
const { username, email, password } = req.body;
// In a real app, you would hash the password, save to DB, etc.
console.log(`User registered: ${username}, ${email}`);
res.status(201).json({ message: 'User registered successfully!' });
}
);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});