Skip to main content
Version: 7.2.0

ExpressValidator

ExpressValidator

import { ExpressValidator } from 'express-validator';
new ExpressValidator(
customValidators?: Record<string, CustomValidator>,
customSanitizers?: Record<string, CustomSanitizer>,
options?: {
errorFormatter: ErrorFormatter<E>;
}
);

ExpressValidator is a class which wraps the entire express-validator API, with some differences:

  1. you can specify custom validators and/or custom sanitizers that are always available in validation chains;
  2. you can specify options that apply by default to some functions.

customValidators and customSanitizers are objects from custom validator/sanitizer name to implementation.
See examples in the usage section, and see the "Custom Validators and Sanitizers" guide to learn more.

If options.errorFormatter is set, it's used as the default error formatter used by .validationResult().

Usage

With custom validators only

const { body } = new ExpressValidator({
isEmailNotInUse: async value => {
const user = await Users.findByEmail(value);
if (user) {
throw new Error('E-mail already in use');
}
},
});

app.post('/signup', body('email').isEmailNotInUse(), (req, res) => {});

With custom sanitizers only

const { body } = new ExpressValidator({}, {
muteOffensiveWords: async value => {
for (const word of offensiveWords) {
value = value.replaceAll(new RegExp(`\\b${word}\\b`), word[0].padEnd(word.length, '*'));
}
return value;
},
});

app.post('/add-comment', body('comment').muteOffensiveWords(), (req, res) => {});

.check()

check(fields?: string | string[], message?: any): CustomValidationChain<T>

Same as standalone check() function, but returning a CustomValidationChain for that ExpressValidator instance.

.body()

body(fields?: string | string[], message?: any): CustomValidationChain<T>

Same as standalone body() function, but returning a CustomValidationChain for that ExpressValidator instance.

cookie(fields?: string | string[], message?: any): CustomValidationChain<T>

Same as standalone cookie() function, but returning a CustomValidationChain for that ExpressValidator instance.

header(fields?: string | string[], message?: any): CustomValidationChain<T>

Same as standalone header() function, but returning a CustomValidationChain for that ExpressValidator instance.

.param()

param(fields?: string | string[], message?: any): CustomValidationChain<T>

Same as standalone param() function, but returning a CustomValidationChain for that ExpressValidator instance.

.query()

query(fields?: string | string[], message?: any): CustomValidationChain<T>

Same as standalone query() function, but returning a CustomValidationChain for that ExpressValidator instance.

.buildCheckFunction()

.checkExact()

Same as standalone checkExact() function. Only present in ExpressValidator for convenience.

.checkSchema()

checkSchema(schema: CustomSchema<T>, defaultLocations?: Location[]): CustomValidationChain<T>[]

Same as standalone checkSchema() function, but the schema can reference the custom validators or sanitizers from the ExpressValidator instance.

const { checkSchema } = new ExpressValidator({ isEmailNotInUse });
app.post(
'/signup',
checkSchema({
email: { isEmailNotInUse: true },
}),
(req, res) => {
// handle request
},
);

.matchedData()

Same as standalone matchedData() function. Only present in ExpressValidator for convenience.

.oneOf()

Same as standalone oneOf() function, but accepts CustomValidationChains created from ExpressValidator.

.validationResult()

validationResult(req): Result<E>

Same as standalone validationResult() function, but uses the options.errorFormatter passed in the constructor by default.

const { ExpressValidator } = require('express-validator');

const { query, validationResult } = new ExpressValidator({}, {}, {
errorFormatter: error => error.msg,
};

app.post('/hello', query('person').notEmpty(), (req, res) => {
const result = validationResult(req);
const errors = result.array();
// => ['Invalid value', ... ]

const result2 = result.formatWith(error => `${error.msg}!!!`);
const errors2 = result2.array();
// => ['Invalid value!!!']
});

CustomSchema

The type of a schema created through ExpressValidator.

Has a single generic parameter T, which is the type of the ExpressValidator instance.

import { ExpressValidator, CustomSchema } from 'express-validator';

const myExpressValidator = new ExpressValidator({ isEmailNotInUse });
type MyCustomSchema = CustomSchema<typeof myExpressValidator>;

const schema: MyCustomSchema = {
email: { isEmailNotInUse: true },
};

CustomValidationChain

The type of a validation chain created through ExpressValidator.

Has a single generic parameter T, which is the type of the ExpressValidator instance.

import { ExpressValidator, CustomValidationChain } from 'express-validator';

const myExpressValidator = new ExpressValidator({ isEmailNotInUse });
type MyValidationChain = CustomValidationChain<typeof myExpressValidator>;

const chain: MyValidationChain = myExpressValidator.body('email').isEmailNotInUse();