Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

express-validator

Package Overview
Dependencies
Maintainers
3
Versions
121
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

express-validator - npm Package Compare versions

Comparing version 6.8.2 to 6.9.0

55

docs/api-check.md

@@ -9,7 +9,10 @@ ---

## `check([field, message])`
- `field` *(optional)*: a string or an array of strings of field names to validate against.
- `message` *(optional)*: an error message to use when failed validators don't specify a message. Defaults to `Invalid value`; see also [Dynamic Messages](feature-error-messages.md#dynamic-messages).
> *Returns:* a [Validation Chain](api-validation-chain.md)
- `field` _(optional)_: a string or an array of strings of field names to validate against.
- `message` _(optional)_: an error message to use when failed validators don't specify a message. Defaults to `Invalid value`; see also [Dynamic Messages](feature-error-messages.md#dynamic-messages).
> _Returns:_ a [Validation Chain](api-validation-chain.md)
Creates a validation chain for one or more fields. They may be located in any of the following request objects:
- `req.body`

@@ -30,26 +33,35 @@ - `req.cookies`

## `body([fields, message])`
Same as `check([fields, message])`, but only checking `req.body`.
## `cookie([fields, message])`
Same as `check([fields, message])`, but only checking `req.cookies`.
## `header([fields, message])`
Same as `check([fields, message])`, but only checking `req.headers`.
## `param([fields, message])`
Same as `check([fields, message])`, but only checking `req.params`.
## `query([fields, message])`
Same as `check([fields, message])`, but only checking `req.query`.
## `checkSchema(schema)`
- `schema`: the schema to validate. Must comply with the format described in [Schema Validation](feature-schema-validation.md).
> *Returns:* an array of validation chains
> _Returns:_ an array of validation chains
## `oneOf(validationChains[, message])`
- `validationChains`: an array of [validation chains](api-validation-chain.md) created with `check()` or any of its variations,
or an array of arrays containing validation chains.
- `message` *(optional)*: an error message to use when all chains failed. Defaults to `Invalid value(s)`; see also [Dynamic Messages](feature-error-messages.md#dynamic-messages).
> *Returns:* a middleware instance
- `message` _(optional)_: an error message to use when all chains failed. Defaults to `Invalid value(s)`; see also [Dynamic Messages](feature-error-messages.md#dynamic-messages).
> _Returns:_ a middleware instance
Creates a middleware instance that will ensure at least one of the given chains passes the validation.

@@ -82,14 +94,19 @@ If none of the given chains passes, an error will be pushed to the `_error` pseudo-field,

<!-- prettier-ignore-start -->
```js
// This protected route must be accessed either by passing both username + password,
// or by passing an access token
app.post('/protected/route', oneOf([
[
check('username').exists(),
check('password').exists()
],
check('access_token').exists()
]), someRouteHandler);
app.post(
'/protected/route',
oneOf([
[check('username').exists(), check('password').exists()],
check('access_token').exists()
]),
someRouteHandler,
);
```
<!-- prettier-ignore-end -->
The execution of those validation chains are made in parallel,

@@ -99,6 +116,8 @@ while the execution within a chain still respects the rule defined in the [`check()` function](#check-field-message).

## `buildCheckFunction(locations)`
- `locations`: an array of request locations to gather data from.
May include any of `body`, `cookies`, `headers`, `params` or `query`.
> *Returns:* a variant of [`check()`](#check-field-message) checking the given request locations.
> _Returns:_ a variant of [`check()`](#check-field-message) checking the given request locations.
Creates a variant of [`check()`](#check-field-message) that checks the given request locations.

@@ -110,6 +129,8 @@

app.put('/update-product', [
app.put(
'/update-product',
// id must be either in req.body or req.query, and must be an UUID
checkBodyAndQuery('id').isUUID()
], productUpdateHandler)
checkBodyAndQuery('id').isUUID(),
productUpdateHandler,
);
```

@@ -9,12 +9,15 @@ ---

> These sanitization-only middlewares have been deprecated, as **the [validation middlewares](api-check.md)
offer the same functionality**, and much more.
> offer the same functionality**, and much more.
> They will be removed eventually.
## `sanitize(fields)`
- `field`: a string or an array of strings of field names to validate against.
> *Returns:* a [Sanitization Chain](api-sanitization-chain.md)
> _Returns:_ a [Sanitization Chain](api-sanitization-chain.md)
> [Prefer using `check()` instead](api-check.md#checkfields-message). This function has been deprecated.
Creates a sanitization chain for one or more fields. They may be located in any of the following request objects:
- `req.body`

@@ -25,3 +28,3 @@ - `req.cookies`

_* `req.headers` is **not** supported at the moment._
_\* `req.headers` is **not** supported at the moment._

@@ -31,2 +34,3 @@ If any of the fields are present in more than one location, then all instances of that field value will be sanitized.

## `sanitizeBody(fields)`
Same as `sanitize(fields)`, but only sanitizing `req.body`.

@@ -37,2 +41,3 @@

## `sanitizeCookie(fields)`
Same as `sanitize(fields)`, but only sanitizing `req.cookies`.

@@ -43,2 +48,3 @@

## `sanitizeParam(fields)`
Same as `sanitize(fields)`, but only sanitizing `req.params`.

@@ -49,2 +55,3 @@

## `sanitizeQuery(fields)`
Same as `sanitize(fields)`, but only sanitizing `req.query`.

@@ -55,6 +62,8 @@

## `buildSanitizeFunction(locations)`
- `locations`: an array of request locations to gather data from.
May include any of `body`, `cookies`, `params` or `query`.
> *Returns:* a variant of [`sanitize()`](#sanitizefields) sanitizing the given request locations.
> _Returns:_ a variant of [`sanitize()`](#sanitizefields) sanitizing the given request locations.
> [Prefer using `buildCheckFunction()` instead](api-check.md#buildcheckfunctionlocations). This function has been deprecated.

@@ -68,6 +77,8 @@

app.put('/update-product', [
app.put(
'/update-product',
// id being either in req.body or req.query will be converted to int
sanitizeBodyAndQuery('id').toInt()
], productUpdateHandler)
```
sanitizeBodyAndQuery('id').toInt(),
productUpdateHandler,
);
```

@@ -9,4 +9,5 @@ ---

## `matchedData(req[, options])`
- `req`: the express request object.
- `options` *(optional)*: an object which accepts the following options:
- `options` _(optional)_: an object which accepts the following options:
- `includeOptionals`: if set to `true`, the returned value includes optional data. Defaults to `false`.

@@ -17,4 +18,5 @@ - `onlyValidData`: if set to `false`, the returned value includes data from fields

`body`, `cookies`, `headers`, `params` and `query`. Defaults to `undefined`, which means all locations.
> *Returns:* an object of data that express-validator has validated or sanitized.
> _Returns:_ an object of data that express-validator has validated or sanitized.
Extracts data validated or sanitized by express-validator from the request and builds

@@ -25,3 +27,5 @@ an object with them. Nested paths and wildcards are properly handled as well.

## Examples
### Gathering data from multiple locations
If data you validated or sanitized is spread across various request locations

@@ -31,2 +35,4 @@ (e.g. `req.body`, `req.query`, `req.params`, etc), then `matchedData` will gather it properly.

<!-- prettier-ignore-start -->
```js

@@ -47,3 +53,6 @@ // Suppose the request looks like this:

<!-- prettier-ignore-end -->
### Including optional data
You may want to have [optional values](api-validation-chain.md#optionaloptions) among the required ones.

@@ -54,2 +63,4 @@

<!-- prettier-ignore-start -->
```js

@@ -59,11 +70,15 @@ // Suppose the request looks like this:

app.post('/update-user', [
app.post(
'/update-user',
check('name').not().isEmpty(),
check('bio').optional({ checkFalsy: true }).escape(),
], (req, res, next) => {
const requiredData = matchedData(req, { includeOptionals: false });
const allData = matchedData(req, { includeOptionals: true });
console.log(requiredData); // { name: 'John Doe' }
console.log(allData); // { name: 'John Doe', bio: '' }
});
(req, res, next) => {
const requiredData = matchedData(req, { includeOptionals: false });
const allData = matchedData(req, { includeOptionals: true });
console.log(requiredData); // { name: 'John Doe' }
console.log(allData); // { name: 'John Doe', bio: '' }
},
);
```
<!-- prettier-ignore-end -->

@@ -21,2 +21,3 @@ ---

## Standard sanitizers
All sanitizers listed by validator.js are made available within a Sanitization Chain,

@@ -31,9 +32,12 @@ and are called "standard sanitizers" in express-validator.

## Additional methods
In addition to the standard sanitizers, the following methods are also available within a Sanitization Chain:
### `.customSanitizer(sanitizer)`
- `sanitizer(value, { req, location, path })`: the custom sanitizer function.
Receives the value of the field being sanitized, as well as the express request, the location and the field path.
> *Returns:* the current sanitization chain instance
> _Returns:_ the current sanitization chain instance
Adds a custom sanitizer to the current sanitization chain. It must synchronously return the new value.

@@ -45,14 +49,19 @@

const { param } = require('express-validator');
app.get('/object/:id', param('id').customSanitizer((value, { req }) => {
return req.query.type === 'user' ? ObjectId(value) : Number(value);
}), objectHandler)
app.get(
'/object/:id',
param('id').customSanitizer((value, { req }) => {
return req.query.type === 'user' ? ObjectId(value) : Number(value);
}),
objectHandler,
);
```
### `.default(default_value)`
> *Returns:* the current sanitization chain instance
> _Returns:_ the current sanitization chain instance
Replaces the current value with a default one if the current value is included in `['', null, undefined, NaN]`.
```js
app.post('/', [body('username').default('foo')], (req, res, next) => {
app.post('/', body('username').default('foo'), (req, res, next) => {
// 'bar' => 'bar'

@@ -63,10 +72,13 @@ // '' => 'foo'

// NaN => 'foo'
});
```
### `.replace(values_to_replace, new_value)`
> *Returns:* the current sanitization chain instance
> _Returns:_ the current sanitization chain instance
Replaces the current value with a new one if the current value is included in a given Array.
```js
app.post('/', [body('username').replace(['bar', 'BAR'], 'foo')], (req, res, next) => {
app.post('/', body('username').replace(['bar', 'BAR'], 'foo'), (req, res, next) => {
// 'bar_' => 'bar_'

@@ -80,4 +92,5 @@ // 'bar' => 'foo'

### `.run(req)`
> *Returns:* a promise that resolves when the sanitization chain ran.
> _Returns:_ a promise that resolves when the sanitization chain ran.
Runs the current sanitization chain in an imperative way.

@@ -98,4 +111,5 @@

### `.toArray()`
> *Returns:* the current sanitization chain instance
> _Returns:_ the current sanitization chain instance
Converts the value to an array. `undefined` will result in an empty array.

@@ -113,4 +127,5 @@

### `.toLowerCase()`
> *Returns:* the current sanitization chain instance
> _Returns:_ the current sanitization chain instance
Converts the value to lower case. Non string value will return itself.

@@ -128,4 +143,5 @@

### `.toUpperCase()`
> *Returns:* the current sanitization chain instance
> _Returns:_ the current sanitization chain instance
Converts the value to upper case. Non string value will return itself.

@@ -132,0 +148,0 @@

@@ -8,3 +8,3 @@ ---

You can add as many validators and sanitizers to a chain as you need.
You can add as many validators and sanitizers to a chain as you need.
When the middleware runs, it will run each validator or sanitizer in the order they were specified;

@@ -18,2 +18,3 @@ this means if a sanitizer is specified before a validator, the validator will run with the sanitized

## Standard validators
All validators listed by validator.js are made available within a Validation Chain,

@@ -28,2 +29,3 @@ and are called "standard validators" in express-validator.

## Sanitization Chain API
A validation chain also is a subset of the [Sanitization Chain](api-sanitization-chain.md), meaning

@@ -36,3 +38,3 @@ all standard sanitizers and its additional methods are available:

check('email').normalizeEmail().isEmail(),
check('date-of-birth').isISO8601().toDate()
check('date-of-birth').isISO8601().toDate(),
]);

@@ -42,2 +44,3 @@ ```

## Additional methods
In addition to the standard validators and the [Sanitization Chain API](api-sanitization-chain.md),

@@ -47,4 +50,5 @@ the following methods are also available within a Validation Chain:

### `.bail()`
> *Returns:* the current validation chain instance
> _Returns:_ the current validation chain instance
Stops running validations if any of the previous ones have failed.

@@ -70,8 +74,11 @@ Useful to prevent a custom validator that touches a database or external API from running when you

### `.custom(validator)`
- `validator(value, { req, location, path })`: the custom validator function.
Receives the value of the field being validated, as well as the express request, the location and the field path.
> *Returns:* the current validation chain instance
Receives the value of the field being validated, as well as the express request, the location and the field path.
> _Returns:_ the current validation chain instance
Adds a custom validator to the current validation chain.
The custom validator may return a promise to indicate an async validation task.
- If it's rejected, the field is considered invalid;

@@ -85,14 +92,21 @@ - If it's resolved, the field is considered valid **regardless of the returned value**.

```js
app.post('/create-user', [
app.post(
'/create-user',
check('password').exists(),
check('passwordConfirmation', 'passwordConfirmation field must have the same value as the password field')
check(
'passwordConfirmation',
'passwordConfirmation field must have the same value as the password field',
)
.exists()
.custom((value, { req }) => value === req.body.password)
], loginHandler);
.custom((value, { req }) => value === req.body.password),
loginHandler,
);
```
### `.exists(options)`
- `options` *(optional)*: an object of options to customize the behavior of exists.
> *Returns:* the current validation chain instance
- `options` _(optional)_: an object of options to customize the behavior of exists.
> _Returns:_ the current validation chain instance
Adds a validator to check for the existence of the current fields in the request.

@@ -102,2 +116,3 @@ This means the value of the fields may not be `undefined`; all other values are acceptable.

You can customize this behavior by passing an object with the following options:
- `checkNull`: if `true`, fields with `null` values will not exist

@@ -107,8 +122,11 @@ - `checkFalsy`: if `true`, fields with falsy values (eg `""`, `0`, `false`, `null`) will also not exist

### `.if(condition)`
- `condition`: the condition for this Validation Chain to continue validating.
> *Returns:* the current validation chain instance
> _Returns:_ the current validation chain instance
Adds a condition for deciding if validation should continue on a field or not.
The condition can be either:
- A custom validator-like function: `condition(value, { req, path, location })`.

@@ -118,3 +136,4 @@ Receives the value of the field being validated, as well as the express request, the location and the field path.

If it returns truthy or a promise that resolves, the validation chain will continue
running. If it returns falsy, a promise that rejects or if it throws, the validation chain will stop.
running. If it returns falsy, a promise that rejects or if it throws, the validation chain will stop.
- A validation chain [created through `check()` or similar functions](api-check.md#check-field-message).

@@ -131,42 +150,49 @@

// ...then the old password must be too...
.not().empty()
.notEmpty()
// ...and they must not be equal.
.custom((value, { req }) => value !== req.body.newPassword)
.custom((value, { req }) => value !== req.body.newPassword);
```
### `.isArray(options)`
- `options` *(optional)*: an object which accepts the following options:
- `options` _(optional)_: an object which accepts the following options:
- `min`: minimum array length.
- `max`: maximum array length.
> *Returns:* the current validation chain instance
> _Returns:_ the current validation chain instance
Adds a validator to check if a value is an array.
### `.isString()`
> *Returns:* the current validation chain instance
> _Returns:_ the current validation chain instance
Adds a validator to check if a value is a string.
### `.not()`
> *Returns:* the current validation chain instance
> _Returns:_ the current validation chain instance
Negates the result of the next validator.
```js
check('weekday').not().isIn(['sunday', 'saturday'])
check('weekday').not().isIn(['sunday', 'saturday']);
```
### `.notEmpty()`
> *Returns:* the current validation chain instance
> _Returns:_ the current validation chain instance
Adds a validator to check if a value is not empty; that is, a string with a length of 1 or bigger.
```js
check('username').notEmpty()
check('username').notEmpty();
```
### `.optional(options)`
- `options` *(optional)*: an object of options to customize the behaviour of optional.
> *Returns:* the current validation chain instance
- `options` _(optional)_: an object of options to customize the behaviour of optional.
> _Returns:_ the current validation chain instance
Marks the current validation chain as optional.

@@ -178,2 +204,3 @@ This is useful to remove values that are not essential to your business and that would cause validation failures in case they were not provided in the request.

You can customize this behavior by passing an object with the following options:
- `nullable`: if `true`, fields with `null` values will be considered optional

@@ -183,7 +210,9 @@ - `checkFalsy`: if `true`, fields with falsy values (eg `""`, `0`, `false`, `null`) will also be considered optional

### `.run(req[, options])`
- `req`: the current express request to validate.
- `options` *(optional)*: an object of options to customize how the chain will be run:
- `options` _(optional)_: an object of options to customize how the chain will be run:
- `dryRun`: defines whether errors and sanitizations won't be persisted to `req`. Defaults to `false`.
> *Returns:* a promise for a [`Result`](api-validation-result.md#result) that resolves when the validation chain ran.
> _Returns:_ a promise for a [`Result`](api-validation-result.md#result) that resolves when the validation chain ran.
Runs the current validation chain in an imperative way.

@@ -210,3 +239,6 @@

app.post('/api/*', async (req, res, next) => {
const tokenResult = await check('token').notEmpty().custom(checkMyTokenFormat).run(req, { dryRun: true });
const tokenResult = await check('token')
.notEmpty()
.custom(checkMyTokenFormat)
.run(req, { dryRun: true });
if (tokenResult.isEmpty()) {

@@ -223,3 +255,3 @@ // The token looks good, so try to authenticate it

await check('done').isBoolean().run(req);
const result = validationResult(req);

@@ -234,5 +266,7 @@ if (!result.isEmpty()) {

### `.withMessage(message)`
- `message`: the error message to use for the previous validator
> *Returns:* the current validation chain instance
> _Returns:_ the current validation chain instance
Sets the error message for the previous validator.

@@ -239,0 +273,0 @@ This will have precedence over errors thrown by a custom validator.

@@ -9,5 +9,7 @@ ---

## `validationResult(req)`
- `req`: the express request object
> *Returns:* a [`Result`](#result) object
> _Returns:_ a [`Result`](#result) object
Extracts the validation errors from a request and makes them available in a [`Result`](#result) object.

@@ -32,7 +34,8 @@

### `.withDefaults(options)`
- `options` *(optional)*: an object of options. Defaults to `{ formatter: error => error }`
> *Returns:* a new [`validationResult`](#validationresultreq) function, using the provided options
- `options` _(optional)_: an object of options. Defaults to `{ formatter: error => error }`
> _Returns:_ a new [`validationResult`](#validationresultreq) function, using the provided options
Creates a new `validationResult()`-like function with default options passed to the generated

@@ -47,7 +50,7 @@ [`Result`](#result) instance.

const myValidationResult = validationResult.withDefaults({
formatter: (error) => {
formatter: error => {
return {
myLocation: error.location,
};
}
},
});

@@ -62,2 +65,3 @@

## `Result`
An object that holds the current state of validation errors in a request and allows access to it in

@@ -67,4 +71,5 @@ a variety of ways.

### `.isEmpty()`
> *Returns:* a boolean indicating whether this result object contains no errors at all.
> _Returns:_ a boolean indicating whether this result object contains no errors at all.
```js

@@ -79,6 +84,8 @@ app.post('/create-user', yourValidationChains, (req, res) => {

### `.formatWith(formatter)`
- `formatter(error)`: the function to use to format when returning errors.
The `error` argument is an object in the format of `{ location, msg, param, value, nestedErrors }`, as described above.
> *Returns:* a new `Result` instance
The `error` argument is an object in the format of `{ location, msg, param, value, nestedErrors }`, as described above.
> _Returns:_ a new `Result` instance
```js

@@ -102,5 +109,7 @@ app.post('/create-user', yourValidationChains, (req, res, next) => {

### `.array([options])`
- `options` *(optional)*: an object of options. Defaults to `{ onlyFirstError: false }`
> *Returns:* an array of validation errors.
- `options` _(optional)_: an object of options. Defaults to `{ onlyFirstError: false }`
> _Returns:_ an array of validation errors.
Gets all validation errors contained in this result object.

@@ -112,7 +121,9 @@

### `.mapped()`
> *Returns:* an object where the keys are the field names, and the values are the validation errors
> _Returns:_ an object where the keys are the field names, and the values are the validation errors
Gets the first validation error of each failed field in the form of an object.
### `.throw()`
If this result object has errors, then this method will throw an exception

@@ -119,0 +130,0 @@ decorated with the same validation result API.

@@ -13,2 +13,3 @@ ---

## Custom validator
A custom validator may be implemented by using the chain method [`.custom()`](api-validation-chain.md#customvalidator).

@@ -23,33 +24,44 @@ It takes a validator function.

### Example: checking if e-mail is in use
```js
const { body } = require('express-validator');
app.post('/user', body('email').custom(value => {
return User.findUserByEmail(value).then(user => {
if (user) {
return Promise.reject('E-mail already in use');
}
});
}), (req, res) => {
// Handle the request
});
app.post(
'/user',
body('email').custom(value => {
return User.findUserByEmail(value).then(user => {
if (user) {
return Promise.reject('E-mail already in use');
}
});
}),
(req, res) => {
// Handle the request
},
);
```
### Example: checking if password confirmation matches password
```js
const { body } = require('express-validator');
app.post('/user', body('passwordConfirmation').custom((value, { req }) => {
if (value !== req.body.password) {
throw new Error('Password confirmation does not match password');
}
// Indicates the success of this synchronous custom validator
return true;
}), (req, res) => {
// Handle the request
});
app.post(
'/user',
body('passwordConfirmation').custom((value, { req }) => {
if (value !== req.body.password) {
throw new Error('Password confirmation does not match password');
}
// Indicates the success of this synchronous custom validator
return true;
}),
(req, res) => {
// Handle the request
},
);
```
## Custom sanitizers
Custom sanitizers can be implemented by using the method `.customSanitizer()`, no matter if

@@ -62,10 +74,15 @@ the [validation chain one](api-validation-chain.md#customsanitizersanitizer) or

### Example: converting to MongoDB's ObjectID
```js
const { param } = require('express-validator');
app.post('/object/:id', param('id').customSanitizer(value => {
return ObjectId(value);
}), (req, res) => {
// Handle the request
});
app.post(
'/object/:id',
param('id').customSanitizer(value => {
return ObjectId(value);
}),
(req, res) => {
// Handle the request
},
);
```

@@ -12,3 +12,5 @@ ---

## Error message levels
### Validator Level
When you want fine grained control over the error message of each validator,

@@ -20,10 +22,14 @@ you may specify them using the [`.withMessage()` method](api-validation-chain.md#withmessagemessage).

app.post('/user', [
app.post(
'/user',
// ...some other validations...
check('password')
.isLength({ min: 5 }).withMessage('must be at least 5 chars long')
.matches(/\d/).withMessage('must contain a number')
], (req, res) => {
// Handle the request somehow
});
.isLength({ min: 5 })
.withMessage('must be at least 5 chars long')
.matches(/\d/)
.withMessage('must contain a number'),
(req, res) => {
// Handle the request somehow
},
);
```

@@ -37,2 +43,3 @@

### Custom Validator Level
If you're using a custom validator, then it may very well throw or reject promises to indicate an invalid value.

@@ -44,3 +51,4 @@ In these cases, the error gets reported with a message that's equal to what was thrown by the validator:

app.post('/user', [
app.post(
'/user',
check('email').custom(value => {

@@ -57,9 +65,11 @@ return User.findByEmail(value).then(user => {

}
})
], (req, res) => {
// Handle the request somehow
});
}),
(req, res) => {
// Handle the request somehow
},
);
```
### Field Level
Messages can be specified at the field level by using the second parameter of the

@@ -73,11 +83,15 @@ [validation middlewares](api-check.md#check-field-message).

app.post('/user', [
app.post(
'/user',
// ...some other validations...
check('password', 'The password must be 5+ chars long and contain a number')
.not().isIn(['123', 'password', 'god']).withMessage('Do not use a common word as the password')
.not()
.isIn(['123', 'password', 'god'])
.withMessage('Do not use a common word as the password')
.isLength({ min: 5 })
.matches(/\d/)
], (req, res) => {
// Handle the request somehow
});
.matches(/\d/),
(req, res) => {
// Handle the request somehow
},
);
```

@@ -94,2 +108,4 @@

<!-- prettier-ignore-start -->
```js

@@ -105,5 +121,7 @@ // check(field, withMessage) and .withMessage() work the same

// oneOf is special though - it only receives the req object for now
oneOf([ someValidation, anotherValidation ], ({ req }) => {
oneOf([someValidation, anotherValidation], ({ req }) => {
return req.translate('validation.multiple_failures');
});
```
<!-- prettier-ignore-end -->

@@ -16,2 +16,3 @@ ---

## Example: standardized validation error response
```js

@@ -48,6 +49,6 @@ // can be reused by many routes

res.status(400).json({ errors: errors.array() });
}
};
};
```
```
```js

@@ -63,18 +64,21 @@ app.post('/api/create-user', validate([

## Example: validating with a condition
## Example: validating with a condition
```js
app.post('/update-settings', [
app.post(
'/update-settings',
body('email').isEmail(),
body('password').optional().isLength({ min: 6 })
], async (req, res, next) => {
// if a password has been provided, then a confirmation must also be provided.
if (req.body.password) {
await body('passwordConfirmation')
.equals(req.body.password).withMessage('passwords do not match')
.run(req);
}
body('password').optional().isLength({ min: 6 }),
async (req, res, next) => {
// if a password has been provided, then a confirmation must also be provided.
if (req.body.password) {
await body('passwordConfirmation')
.equals(req.body.password)
.withMessage('passwords do not match')
.run(req);
}
// Check the validation errors, and update the user's settings.
});
// Check the validation errors, and update the user's settings.
},
);
```

@@ -19,14 +19,11 @@ ---

app.post('/comment', [
body('email')
.isEmail()
.normalizeEmail(),
body('text')
.not().isEmpty()
.trim()
.escape(),
body('notifyOnReply').toBoolean()
], (req, res) => {
// Handle the request somehow
});
app.post(
'/comment',
body('email').isEmail().normalizeEmail(),
body('text').not().isEmpty().trim().escape(),
body('notifyOnReply').toBoolean(),
(req, res) => {
// Handle the request somehow
},
);
```

@@ -41,3 +38,3 @@

> **Important:** please note that sanitization mutates the request.
This means that if `req.body.text` was sent with the value ` Hello world :>)`, after the sanitization
its value will be `Hello world :&gt;)`.
> This means that if `req.body.text` was sent with the value ` Hello world :>)`, after the sanitization
> its value will be `Hello world :&gt;)`.

@@ -14,60 +14,70 @@ ---

const { checkSchema } = require('express-validator');
app.put('/user/:id/password', checkSchema({
id: {
// The location of the field, can be one or more of body, cookies, headers, params or query.
// If omitted, all request locations will be checked
in: ['params', 'query'],
errorMessage: 'ID is wrong',
isInt: true,
// Sanitizers can go here as well
toInt: true
},
myCustomField: {
// Custom validators
custom: {
options: (value, { req, location, path }) => {
return value + req.body.foo + location + path;
}
app.put(
'/user/:id/password',
checkSchema({
id: {
// The location of the field, can be one or more of body, cookies, headers, params or query.
// If omitted, all request locations will be checked
in: ['params', 'query'],
errorMessage: 'ID is wrong',
isInt: true,
// Sanitizers can go here as well
toInt: true,
},
// and sanitizers
customSanitizer: {
options: (value, { req, location, path }) => {
let sanitizedValue;
myCustomField: {
// Custom validators
custom: {
options: (value, { req, location, path }) => {
return value + req.body.foo + location + path;
},
},
// and sanitizers
customSanitizer: {
options: (value, { req, location, path }) => {
let sanitizedValue;
if (req.body.foo && location && path) {
sanitizedValue = parseInt(value);
} else {
sanitizedValue = 0;
}
if (req.body.foo && location && path) {
sanitizedValue = parseInt(value);
} else {
sanitizedValue = 0;
}
return sanitizedValue;
}
return sanitizedValue;
},
},
},
},
password: {
isLength: {
errorMessage: 'Password should be at least 7 chars long',
// Multiple options would be expressed as an array
options: { min: 7 }
}
},
firstName: {
isUppercase: {
// To negate a validator
negated: true,
password: {
isLength: {
errorMessage: 'Password should be at least 7 chars long',
// Multiple options would be expressed as an array
options: { min: 7 },
},
},
rtrim: {
// Options as an array
options: [[" ", "-"]],
firstName: {
isUppercase: {
// To negate a validator
negated: true,
},
rtrim: {
// Options as an array
options: [[' ', '-']],
},
},
// Support bail functionality in schemas
email: {
isEmail: {
bail: true,
},
},
// Wildcards/dots for nested fields work as well
'addresses.*.postalCode': {
// Make this field optional when undefined or null
optional: { options: { nullable: true } },
isPostalCode: true,
},
}),
(req, res, next) => {
// handle the request as usual
},
// Wildcards/dots for nested fields work as well
'addresses.*.postalCode': {
// Make this field optional when undefined or null
optional: { options: { nullable: true } },
isPostalCode: true
}
}), (req, res, next) => {
// handle the request as usual
})
);
```

@@ -21,11 +21,14 @@ ---

app.post('/addresses', [
app.post(
'/addresses',
check('addresses.*.postalCode').isPostalCode(),
sanitize('addresses.*.number').toInt()
], (req, res) => {
// Handle the request
});
sanitize('addresses.*.number').toInt(),
(req, res) => {
// Handle the request
},
);
```
This will handle cases where you send an array of addresses:
```json

@@ -35,3 +38,3 @@ {

{ "postalCode": "2010", "number": "500" },
{ "postalCode": "", "number": "501" },
{ "postalCode": "", "number": "501" }
]

@@ -42,2 +45,3 @@ }

...or even cases where you want a predefined set of addresses:
```json

@@ -44,0 +48,0 @@ {

@@ -10,2 +10,3 @@ ---

## Installation
Install it using npm (make sure that you have Node.js 8 or newer):

@@ -18,4 +19,5 @@

## Basic guide
> It's recommended that you have basic knowledge of the express.js module before you go on with
this guide.
> this guide.

@@ -32,3 +34,3 @@ Let's get started by writing a basic route to create a user in the database:

username: req.body.username,
password: req.body.password
password: req.body.password,
}).then(user => res.json(user));

@@ -44,30 +46,35 @@ });

app.post('/user', [
app.post(
'/user',
// username must be an email
body('username').isEmail(),
// password must be at least 5 chars long
body('password').isLength({ min: 5 })
], (req, res) => {
// Finds the validation errors in this request and wraps them in an object with handy functions
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
body('password').isLength({ min: 5 }),
(req, res) => {
// Finds the validation errors in this request and wraps them in an object with handy functions
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
User.create({
username: req.body.username,
password: req.body.password
}).then(user => res.json(user));
});
User.create({
username: req.body.username,
password: req.body.password,
}).then(user => res.json(user));
},
);
```
*Voila!* Now, whenever a request that includes invalid `username` or `password` fields
_Voila!_ Now, whenever a request that includes invalid `username` or `password` fields
is submitted, your server will respond like this:
```json
{
"errors": [{
"location": "body",
"msg": "Invalid value",
"param": "username"
}]
"errors": [
{
"location": "body",
"msg": "Invalid value",
"param": "username"
}
]
}

@@ -80,2 +87,3 @@ ```

## What's next
This completes the basic guide on getting started with express-validator.

@@ -82,0 +90,0 @@ You might want to continue reading about some of the more advanced features available:

@@ -10,3 +10,3 @@ {

],
"version": "6.8.2",
"version": "6.9.0",
"homepage": "https://express-validator.github.io",

@@ -38,3 +38,3 @@ "license": "MIT",

"test": "jest",
"lint": "eslint --ignore-path .gitignore 'src/**/*.ts'",
"lint": "eslint --ignore-path .gitignore 'src/**/*.ts' && prettier -c .",
"report-coverage": "cat coverage/lcov.info | coveralls",

@@ -41,0 +41,0 @@ "version": "npm run docs:version -- $npm_package_version && npm run docs:build && git add -A website"

@@ -8,4 +8,4 @@ # express-validator

An [express.js]( https://github.com/visionmedia/express ) middleware for
[validator]( https://github.com/chriso/validator.js ).
An [express.js](https://github.com/visionmedia/express) middleware for
[validator](https://github.com/chriso/validator.js).

@@ -18,2 +18,3 @@ - [Installation](#installation)

## Installation
```

@@ -26,2 +27,3 @@ npm install express-validator

## Documentation
Please refer to the documentation website on https://express-validator.github.io.

@@ -28,0 +30,0 @@

@@ -9,2 +9,3 @@ import { Sanitizers } from '../chain/sanitizers';

negated?: boolean;
bail?: boolean;
};

@@ -11,0 +12,0 @@ export declare type ValidatorsSchema = {

@@ -34,2 +34,5 @@ "use strict";

}
if (isValidatorOptions(method, methodCfg) && methodCfg.bail) {
chain.bail();
}
});

@@ -36,0 +39,0 @@ return chain;

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc