Registry / web-framework / express-validator

express-validator

JSON →
library7.3.2jsnpmunverified

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.

npm install express-validator
INSTALL
IMPORT
SIG · EXPRESS-VALIDATOR
E
express-validator
web-frameworkjavascriptv7.3.2
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

check
import { check } from 'express-validator';
const { check } = require('express-validator/check');
Since v7.0.0, import paths like `express-validator/check` and `express-validator/filter` have been removed. All core validation functions are now directly imported from 'express-validator'.
body
import { body } from 'express-validator';
import * as expressValidator from 'express-validator'; const body = expressValidator.body;
`body` is a named export for validating fields specifically within `req.body`. CommonJS users would use `const { body } = require('express-validator');`.
validationResult
import { validationResult } from 'express-validator';
import validationResult from 'express-validator/validationResult';
`validationResult` is a named export that provides an object with methods to retrieve errors collected by the validation middleware. It is crucial for handling validation outcomes.
checkSchema
import { checkSchema } from 'express-validator';
`checkSchema` is used for defining validation rules using a schema object, offering a declarative way to validate multiple fields.

This quickstart demonstrates setting up an Express endpoint that uses `express-validator` to validate and sanitize user registration input. It checks for a non-empty username, a valid email format, and a minimum password length, returning appropriate error responses if validation fails.

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}`); });
Debug
Known issues
breakingExpress-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.
fix
Upgrade your Node.js environment to version 14 or newer. Consult your hosting provider or `nvm` for managing Node.js versions.
affects: >=7.0.0
breakingWith 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.
fix
Update all imports to use the unified `import { ... } from 'express-validator';` syntax and replace removed sanitization-only middlewares with validation chains that include sanitizers (e.g., `body('field').trim().escape()`).
affects: >=7.0.0
gotchaPrior 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.
fix
Upgrade to `express-validator` v7.2.1 or higher to ensure non-primitive replacement values are correctly cloned, preventing object reference issues. If upgrading is not possible, manually clone objects/arrays before passing them to these methods.
affects: <7.2.1
gotchaThe `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.
fix
If your application relies on `isObject()` allowing arrays or `null`, explicitly set `options.strict: false` in your `isObject()` validator chain (e.g., `body('myField').isObject({ strict: false })`).
affects: >=7.0.0
breakingThe 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.
fix
Review the migration guide from v6 to v7 on the official documentation for detailed changes to error structures and `oneOf()` usage. Adjust error handling logic and `oneOf()` calls accordingly.
affects: >=7.0.0
Errors
Common errors & fixes
TypeError: (0 , express_validator__WEBPACK_IMPORTED_MODULE_2__.check) is not a function
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`.
fix
Ensure 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
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.
fix
After 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
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.
fix
In 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()`)
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.
fix
Ensure 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) => { /* ... */ });`.
Upgrade
Version history
7.3.2latest on npm
Audit
Dependencies
expressrequiredexpress-validator is an Express.js middleware and requires an Express application to function. It is verified to work with express.js 4.x.
validatorrequiredThis package is a wrapper around the `validator.js` library, providing its core validation and sanitization logic.
Agent activity
21 hits · last 30 days
node
18
OpenAI (training)
1
Resources