{"id":17096,"library":"express-validator","title":"express-validator","description":"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.","status":"active","version":"7.3.2","language":"javascript","source_language":"en","source_url":"git://github.com/express-validator/express-validator","tags":["javascript","express","validator","validation","validate","sanitize","sanitization","xss","typescript"],"install":[{"cmd":"npm install express-validator","lang":"bash","label":"npm"},{"cmd":"yarn add express-validator","lang":"bash","label":"yarn"},{"cmd":"pnpm add express-validator","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"express-validator is an Express.js middleware and requires an Express application to function. It is verified to work with express.js 4.x.","package":"express","optional":false},{"reason":"This package is a wrapper around the `validator.js` library, providing its core validation and sanitization logic.","package":"validator","optional":false}],"imports":[{"note":"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'.","wrong":"const { check } = require('express-validator/check');","symbol":"check","correct":"import { check } from 'express-validator';"},{"note":"`body` is a named export for validating fields specifically within `req.body`. CommonJS users would use `const { body } = require('express-validator');`.","wrong":"import * as expressValidator from 'express-validator'; const body = expressValidator.body;","symbol":"body","correct":"import { body } from 'express-validator';"},{"note":"`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.","wrong":"import validationResult from 'express-validator/validationResult';","symbol":"validationResult","correct":"import { validationResult } from 'express-validator';"},{"note":"`checkSchema` is used for defining validation rules using a schema object, offering a declarative way to validate multiple fields.","symbol":"checkSchema","correct":"import { checkSchema } from 'express-validator';"}],"quickstart":{"code":"import express from 'express';\nimport { body, validationResult } from 'express-validator';\n\nconst app = express();\napp.use(express.json()); // Middleware to parse JSON bodies\n\napp.post('/register',\n  body('username').notEmpty().withMessage('Username is required').trim().escape(),\n  body('email').isEmail().withMessage('Must be a valid email address').normalizeEmail(),\n  body('password').isLength({ min: 6 }).withMessage('Password must be at least 6 characters long'),\n  async (req, res) => {\n    const errors = validationResult(req);\n    if (!errors.isEmpty()) {\n      return res.status(400).json({ errors: errors.array() });\n    }\n\n    // If validation passes, process the registration\n    const { username, email, password } = req.body;\n    // In a real app, you would hash the password, save to DB, etc.\n    console.log(`User registered: ${username}, ${email}`);\n    res.status(201).json({ message: 'User registered successfully!' });\n  }\n);\n\nconst PORT = process.env.PORT || 3000;\napp.listen(PORT, () => {\n  console.log(`Server running on port ${PORT}`);\n});","lang":"typescript","description":"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."},"warnings":[{"fix":"Upgrade your Node.js environment to version 14 or newer. Consult your hosting provider or `nvm` for managing Node.js versions.","message":"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.","severity":"breaking","affected_versions":">=7.0.0"},{"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()`).","message":"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.","severity":"breaking","affected_versions":">=7.0.0"},{"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.","message":"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.","severity":"gotcha","affected_versions":"<7.2.1"},{"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 })`).","message":"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.","severity":"gotcha","affected_versions":">=7.0.0"},{"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.","message":"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.","severity":"breaking","affected_versions":">=7.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"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');`.","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`.","error":"TypeError: (0 , express_validator__WEBPACK_IMPORTED_MODULE_2__.check) is not a function"},{"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.","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.","error":"Validation chain is not working / Not throwing errors"},{"fix":"In ES module contexts, use `import` statements instead of `require()`: `import { body, validationResult } from 'express-validator';`.","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.","error":"ReferenceError: require is not defined"},{"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) => { /* ... */ });`.","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.","error":"VS Code / IDE does not show suggestions for validation methods (e.g., `.isEmail()`, `.isLength()`)"}],"ecosystem":"npm","meta_description":null}