Express-Validator is a comprehensive request validation and sanitization middleware for Express.js applications. It provides a chainable API for validating and sanitizing request data including body, query parameters, headers, cookies, and URL parameters. Built on top of the popular validator.js library, it offers both individual field validation and schema-based validation with detailed error reporting.
npm install express-validatorimport { body, query, param, header, cookie, check, validationResult, matchedData } from "express-validator";For CommonJS:
const { body, query, param, header, cookie, check, validationResult, matchedData } = require("express-validator");import express from "express";
import { body, validationResult } from "express-validator";
const app = express();
app.use(express.json());
// Validation middleware
app.post('/user', [
body('email').isEmail().normalizeEmail(),
body('password').isLength({ min: 6 }),
body('age').isInt({ min: 18 })
], (req, res) => {
// Check for validation errors
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
// Get validated data
const userData = matchedData(req);
res.json({ message: 'User created', data: userData });
});Express-Validator is built around several key components:
body, query, param, etc.) that create validation chains for specific request locationscheckSchema for complex validation rulesvalidationResult and matchedData for extracting validation outcomes and clean dataExpressValidator classCore functions for creating validation chains targeting specific request locations (body, query, params, headers, cookies).
function body(fields?: string | string[], message?: string): ValidationChain;
function query(fields?: string | string[], message?: string): ValidationChain;
function param(fields?: string | string[], message?: string): ValidationChain;
function header(fields?: string | string[], message?: string): ValidationChain;
function cookie(fields?: string | string[], message?: string): ValidationChain;
function check(fields?: string | string[], message?: string): ValidationChain;Comprehensive set of over 80 built-in validators and 20+ sanitizers for common validation needs.
interface ValidationChain {
// Core validators (sample)
isEmail(options?: EmailOptions): ValidationChain;
isInt(options?: IntOptions): ValidationChain;
isLength(options: { min?: number; max?: number }): ValidationChain;
isURL(options?: URLOptions): ValidationChain;
// Core sanitizers (sample)
trim(chars?: string): ValidationChain;
escape(): ValidationChain;
normalizeEmail(options?: NormalizeEmailOptions): ValidationChain;
toInt(radix?: number): ValidationChain;
}Object-based validation approach for complex validation scenarios and reusable validation logic.
function checkSchema(schema: Schema, defaultLocations?: Location[]): ValidationChain[];
interface Schema {
[field: string]: ParamSchema;
}
interface ParamSchema {
in?: Location[];
exists?: boolean | { errorMessage?: string };
optional?: boolean | { nullable?: boolean; checkFalsy?: boolean };
// Plus all validator and sanitizer methods
}Conditional validation, alternative validation, and exact field checking for complex validation scenarios.
function oneOf(
chains: (ValidationChain | ValidationChain[])[],
options?: { message?: string; errorType?: string }
): ContextRunner;
function checkExact(
knownFields: string[],
options?: { message?: string; locations?: Location[] }
): ContextRunner;Extract validation results and clean, validated data from requests.
function validationResult(req: Request): Result;
function matchedData(req: Request, options?: MatchedDataOptions): any;
interface Result {
isEmpty(): boolean;
array(): ValidationError[];
mapped(): Record<string, ValidationError>;
throw(): never;
}Extend express-validator with custom validation logic and sanitization functions.
interface ValidationChain {
custom(validator: CustomValidator): ValidationChain;
customSanitizer(sanitizer: CustomSanitizer): ValidationChain;
}
type CustomValidator = (value: any, meta: Meta) => boolean | Promise<boolean>;
type CustomSanitizer = (value: any, meta: Meta) => any;type Location = 'body' | 'cookies' | 'headers' | 'params' | 'query';
interface Meta {
req: Request;
location: Location;
path: string;
pathValues: readonly (string | string[])[];
}
interface Request {
body?: any;
cookies?: Record<string, any>;
headers?: Record<string, any>;
params?: Record<string, any>;
query?: Record<string, any>;
}
interface ValidationError {
type: 'field';
location: Location;
path: string;
value: any;
msg: string;
}