Comprehensive set of built-in validators and sanitizers for common validation and data cleaning needs. All methods are chainable and can be combined on ValidationChain instances.
Validators for string format and content validation.
interface ValidationChain {
// Email validation
isEmail(options?: {
allow_display_name?: boolean;
require_display_name?: boolean;
allow_utf8_local_part?: boolean;
require_tld?: boolean;
blacklisted_chars?: string;
ignore_max_length?: boolean;
domain_specific_validation?: boolean;
}): ValidationChain;
// URL validation
isURL(options?: {
protocols?: string[];
require_tld?: boolean;
require_protocol?: boolean;
require_host?: boolean;
require_port?: boolean;
require_valid_protocol?: boolean;
allow_underscores?: boolean;
host_whitelist?: (string | RegExp)[];
host_blacklist?: (string | RegExp)[];
allow_trailing_dot?: boolean;
allow_protocol_relative_urls?: boolean;
allow_fragments?: boolean;
allow_query_components?: boolean;
disallow_auth?: boolean;
validate_length?: boolean;
}): ValidationChain;
// String length validation
isLength(options: { min?: number; max?: number }): ValidationChain;
// UUID validation
isUUID(version?: 1 | 2 | 3 | 4 | 5 | '1' | '2' | '3' | '4' | '5' | 'all'): ValidationChain;
// Alphabetic characters
isAlpha(locale?: string): ValidationChain;
// Alphanumeric characters
isAlphanumeric(locale?: string): ValidationChain;
// Numeric strings
isNumeric(options?: { no_symbols?: boolean; locale?: string }): ValidationChain;
// JSON validation
isJSON(options?: { allow_primitives?: boolean }): ValidationChain;
// Slug validation
isSlug(): ValidationChain;
// Strong password validation
isStrongPassword(options?: {
minLength?: number;
minLowercase?: number;
minUppercase?: number;
minNumbers?: number;
minSymbols?: number;
returnScore?: boolean;
pointsPerUnique?: number;
pointsPerRepeat?: number;
pointsForContainingLower?: number;
pointsForContainingUpper?: number;
pointsForContainingNumber?: number;
pointsForContainingSymbol?: number;
}): ValidationChain;
}Validators for numeric values and ranges.
interface ValidationChain {
// Integer validation
isInt(options?: {
min?: number;
max?: number;
allow_leading_zeroes?: boolean;
lt?: number;
gt?: number;
}): ValidationChain;
// Float validation
isFloat(options?: {
min?: number;
max?: number;
lt?: number;
gt?: number;
locale?: string;
}): ValidationChain;
// Decimal validation
isDecimal(options?: {
force_decimal?: boolean;
decimal_digits?: string;
locale?: string;
}): ValidationChain;
// Divisible by validation
isDivisibleBy(number: number): ValidationChain;
}Validators for date and time values.
interface ValidationChain {
// Date validation
isDate(options?: {
format?: string;
strictMode?: boolean;
delimiters?: string[];
}): ValidationChain;
// ISO 8601 date validation
isISO8601(options?: {
strict?: boolean;
strictSeparator?: boolean;
}): ValidationChain;
// Date range validation
isAfter(date?: string): ValidationChain;
isBefore(date?: string): ValidationChain;
}Validators for boolean values and field existence.
interface ValidationChain {
// Boolean validation
isBoolean(options?: { loose?: boolean }): ValidationChain;
// Field existence
exists(options?: {
checkNull?: boolean;
checkFalsy?: boolean;
}): ValidationChain;
// Not empty validation
notEmpty(options?: { ignore_whitespace?: boolean }): ValidationChain;
}Validators for specific formats and patterns.
interface ValidationChain {
// Credit card validation
isCreditCard(): ValidationChain;
// IP address validation
isIP(version?: 4 | 6): ValidationChain;
// MAC address validation
isMACAddress(options?: { no_colons?: boolean }): ValidationChain;
// Postal code validation
isPostalCode(locale: string): ValidationChain;
// Phone number validation
isMobilePhone(locale: string | string[], options?: {
strictMode?: boolean;
}): ValidationChain;
// Currency validation
isCurrency(options?: {
symbol?: string;
require_symbol?: boolean;
allow_space_after_symbol?: boolean;
symbol_after_digits?: boolean;
allow_negatives?: boolean;
parens_for_negatives?: boolean;
negative_sign_before_digits?: boolean;
negative_sign_after_digits?: boolean;
allow_negative_sign_placeholder?: boolean;
thousands_separator?: string;
decimal_separator?: string;
allow_decimal?: boolean;
require_decimal?: boolean;
digits_after_decimal?: number[];
allow_space_after_digits?: boolean;
}): ValidationChain;
// Regular expression validation
matches(pattern: string | RegExp, modifiers?: string): ValidationChain;
}Validators for value comparisons and constraints.
interface ValidationChain {
// Equality validation
equals(comparison: string): ValidationChain;
// Value containment
contains(elem: any): ValidationChain;
// Array/string inclusion
isIn(values: any[]): ValidationChain;
// Array validation
isArray(options?: { min?: number; max?: number }): ValidationChain;
}Sanitizers for cleaning and transforming string values.
interface ValidationChain {
// Whitespace removal
trim(chars?: string): ValidationChain;
ltrim(chars?: string): ValidationChain;
rtrim(chars?: string): ValidationChain;
// HTML escaping
escape(): ValidationChain;
unescape(): ValidationChain;
// Case conversion
toLowerCase(): ValidationChain;
toUpperCase(): ValidationChain;
// Character filtering
stripLow(keep_new_lines?: boolean): ValidationChain;
blacklist(chars: string): ValidationChain;
whitelist(chars: string): ValidationChain;
// Email normalization
normalizeEmail(options?: {
all_lowercase?: boolean;
gmail_lowercase?: boolean;
gmail_remove_dots?: boolean;
gmail_remove_subaddress?: boolean;
gmail_convert_googlemaildotcom?: boolean;
outlookdotcom_lowercase?: boolean;
outlookdotcom_remove_subaddress?: boolean;
yahoo_lowercase?: boolean;
yahoo_remove_subaddress?: boolean;
icloud_lowercase?: boolean;
icloud_remove_subaddress?: boolean;
}): ValidationChain;
}Sanitizers for converting values to specific types.
interface ValidationChain {
// Numeric conversions
toInt(radix?: number): ValidationChain;
toFloat(): ValidationChain;
// Boolean conversion
toBoolean(strict?: boolean): ValidationChain;
// Date conversion
toDate(): ValidationChain;
// Array conversion
toArray(): ValidationChain;
}Add custom validation and sanitization logic.
interface ValidationChain {
// Custom validation
custom(validator: CustomValidator): ValidationChain;
// Custom sanitization
customSanitizer(sanitizer: CustomSanitizer): ValidationChain;
}
type CustomValidator = (value: any, meta: Meta) => boolean | Promise<boolean>;
type CustomSanitizer = (value: any, meta: Meta) => any;Usage Examples:
import { body } from "express-validator";
// Custom validator
body('username').custom(async (value, { req }) => {
const user = await User.findByUsername(value);
if (user) {
throw new Error('Username already exists');
}
return true;
});
// Custom sanitizer
body('tags').customSanitizer((value) => {
return Array.isArray(value) ? value.map(tag => tag.toLowerCase()) : [];
});Methods for managing field context and error handling behavior.
interface ValidationChain {
/**
* Hide field value in validation errors
* @param hiddenValue - Optional replacement value (default: removes value from error)
* @returns ValidationChain for further chaining
*/
hide(hiddenValue?: string): ValidationChain;
}Usage Examples:
import { body } from "express-validator";
// Hide sensitive field values in error responses
body('apiKey')
.isLength({ min: 32 })
.hide(); // Field value will be removed from errors
// Replace with custom hidden value
body('password')
.isStrongPassword()
.hide('[HIDDEN]'); // Field value will show as '[HIDDEN]' in errors
// Hide credit card numbers
body('creditCard')
.isCreditCard()
.hide('****'); // Field value will show as '****' in errors// Email with normalization
body('email').isEmail().normalizeEmail();
// Password strength
body('password').isStrongPassword({
minLength: 8,
minLowercase: 1,
minUppercase: 1,
minNumbers: 1,
minSymbols: 1
});
// Trim and validate length
body('name').trim().isLength({ min: 2, max: 50 });
// Numeric conversion with range
query('page').isInt({ min: 1 }).toInt();
// Optional field with default sanitization
body('bio').optional().trim().escape();
// Array validation
body('tags').isArray({ min: 1, max: 10 });
body('tags.*').trim().notEmpty();