Skip to content

Commit

Permalink
6.9.0
Browse files Browse the repository at this point in the history
  • Loading branch information
gustavohenke committed Dec 25, 2020
1 parent ab96a77 commit 24b3b93
Show file tree
Hide file tree
Showing 17 changed files with 1,423 additions and 2 deletions.
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Expand Up @@ -7,7 +7,7 @@
"Gustavo Henke <guhenke@gmail.com>",
"Federico Ciardi <fed.ciardi@gmail.com>"
],
"version": "6.8.2",
"version": "6.9.0",
"homepage": "https://express-validator.github.io",
"license": "MIT",
"repository": {
Expand Down
39 changes: 39 additions & 0 deletions website/i18n/en.json
Expand Up @@ -211,6 +211,45 @@
},
"version-6.7.0/version-6.7.0-index": {
"title": "Getting Started"
},
"version-6.9.0/version-6.9.0-check-api": {
"title": "Validation middlewares"
},
"version-6.9.0/version-6.9.0-filter-api": {
"title": "Sanitization middlewares"
},
"version-6.9.0/version-6.9.0-matched-data-api": {
"title": "matchedData()"
},
"version-6.9.0/version-6.9.0-sanitization-chain-api": {
"title": "Sanitization Chain API"
},
"version-6.9.0/version-6.9.0-validation-chain-api": {
"title": "Validation Chain API"
},
"version-6.9.0/version-6.9.0-validation-result-api": {
"title": "validationResult()"
},
"version-6.9.0/version-6.9.0-custom-validators-sanitizers": {
"title": "Custom validators/sanitizers"
},
"version-6.9.0/version-6.9.0-custom-error-messages": {
"title": "Custom Error Messages"
},
"version-6.9.0/version-6.9.0-running-imperatively": {
"title": "Running validations imperatively"
},
"version-6.9.0/version-6.9.0-sanitization": {
"title": "Sanitization"
},
"version-6.9.0/version-6.9.0-schema-validation": {
"title": "Schema Validation"
},
"version-6.9.0/version-6.9.0-wildcards": {
"title": "Wildcards"
},
"version-6.9.0/version-6.9.0-index": {
"title": "Getting Started"
}
},
"links": {
Expand Down
132 changes: 132 additions & 0 deletions website/versioned_docs/version-6.9.0/api-check.md
@@ -0,0 +1,132 @@
---
id: version-6.9.0-check-api
title: Validation middlewares
original_id: check-api
---

These methods are all available via `require('express-validator')`.

## `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)
Creates a validation chain for one or more fields. They may be located in any of the following request objects:

- `req.body`
- `req.cookies`
- `req.headers`
- `req.params`
- `req.query`

If any of the fields are present in more than one location, then all instances of that field value must pass the validation.

**Note:** If `fields` is omitted, then the whole request location will be validated.
This is only useful for `req.body`, though; see [Whole Body Validation](feature-whole-body-validation.md) for examples.

The validators will always be executed serially for the same field.
This means that if the chain targets more than one field, those will run in parallel, but each of their validators are serial.

## `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
## `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
Creates a middleware instance that will ensure at least one of the given chains passes the validation.
If none of the given chains passes, an error will be pushed to the `_error` pseudo-field,
using the given `message`, and the errors of each chain will be made available under a key `nestedErrors`.

Example:

```js
const { check, oneOf, validationResult } = require('express-validator');
app.post('/start-freelancing', oneOf([
check('programming_language').isIn(['javascript', 'java', 'php']),
check('design_tools').isIn(['canva', 'photoshop', 'gimp'])
]), (req, res, next) => {
try {
validationResult(req).throw();

// yay! we're good to start selling our skilled services :)))
res.json(...);
} catch (err) {
// Oh noes. This user doesn't have enough skills for this...
res.status(400).json(...);
}
});
```

If an item of the array is an array containing validation chains, then all of those must pass in order for this
group be considered valid:

<!-- 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,
);
```

<!-- prettier-ignore-end -->

The execution of those validation chains are made in parallel,
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.
Creates a variant of [`check()`](#check-field-message) that checks the given request locations.

```js
const { buildCheckFunction } = require('express-validator');
const checkBodyAndQuery = buildCheckFunction(['body', 'query']);

app.put(
'/update-product',
// id must be either in req.body or req.query, and must be an UUID
checkBodyAndQuery('id').isUUID(),
productUpdateHandler,
);
```
77 changes: 77 additions & 0 deletions website/versioned_docs/version-6.9.0/api-filter.md
@@ -0,0 +1,77 @@
---
id: version-6.9.0-filter-api
title: Sanitization middlewares
original_id: filter-api
---

These methods are all available via `require('express-validator')`.

> These sanitization-only middlewares have been deprecated, as **the [validation middlewares](api-check.md)
> 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)
> [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`
- `req.cookies`
- `req.params`
- `req.query`

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

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`.

> [Prefer using `body()` instead](api-check.md#bodyfields-message). This function has been deprecated.
## `sanitizeCookie(fields)`

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

> [Prefer using `cookie()` instead](api-check.md#cookiefields-message). This function has been deprecated.
## `sanitizeParam(fields)`

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

> [Prefer using `param()` instead](api-check.md#paramfields-message). This function has been deprecated.
## `sanitizeQuery(fields)`

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

> [Prefer using `query()` instead](api-check.md#queryfields-message). This function has been deprecated.
## `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.
> [Prefer using `buildCheckFunction()` instead](api-check.md#buildcheckfunctionlocations). This function has been deprecated.
Creates a variant of [`sanitize()`](#sanitizefields) that sanitizes the given request locations.

```js
const { buildSanitizeFunction } = require('express-validator');
const sanitizeBodyAndQuery = buildSanitizeFunction(['body', 'query']);

app.put(
'/update-product',
// id being either in req.body or req.query will be converted to int
sanitizeBodyAndQuery('id').toInt(),
productUpdateHandler,
);
```
78 changes: 78 additions & 0 deletions website/versioned_docs/version-6.9.0/api-matched-data.md
@@ -0,0 +1,78 @@
---
id: version-6.9.0-matched-data-api
title: matchedData()
original_id: matched-data-api
---

These methods are all available via `require('express-validator')`.

## `matchedData(req[, options])`

- `req`: the express request object.
- `options` _(optional)_: an object which accepts the following options:
- `includeOptionals`: if set to `true`, the returned value includes optional data. Defaults to `false`.
- `onlyValidData`: if set to `false`, the returned value includes data from fields
that didn't pass their validations. Defaults to `true`.
- `locations`: an array of locations to extract the data from. The acceptable values include
`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.
Extracts data validated or sanitized by express-validator from the request and builds
an object with them. Nested paths and wildcards are properly handled as well.
See examples below.

## Examples

### Gathering data from multiple locations

If data you validated or sanitized is spread across various request locations
(e.g. `req.body`, `req.query`, `req.params`, etc), then `matchedData` will gather it properly.
You can also customize which locations you want the data from.

<!-- prettier-ignore-start -->

```js
// Suppose the request looks like this:
// req.query = { from: '2017-01-12' }
// req.body = { to: '2017-31-12' }

app.post('/room-availability', check(['from', 'to']).isISO8601(), (req, res, next) => {
const queryData = matchedData(req, { locations: ['query'] });
const bodyData = matchedData(req, { locations: ['body'] });
const allData = matchedData(req);
console.log(queryData); // { from: '2017-01-12' }
console.log(bodyData); // { to: '2017-31-12' }
console.log(allData); // { from: '2017-01-12', to: '2017-31-12' }
});
```

<!-- prettier-ignore-end -->

### Including optional data

You may want to have [optional values](api-validation-chain.md#optionaloptions) among the required ones.

If they are not included, some databases might understand that you don't want to update those values,
so it's useful to set them to `null` or an empty string.

<!-- prettier-ignore-start -->

```js
// Suppose the request looks like this:
// req.body = { name: 'John Doe', bio: '' }

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: '' }
},
);
```

<!-- prettier-ignore-end -->

0 comments on commit 24b3b93

Please sign in to comment.