UNPKG

2.61 kBMarkdownView Raw
1---
2id: matched-data-api
3title: matchedData()
4---
5
6These methods are all available via `require('express-validator')`.
7
8## `matchedData(req[, options])`
9- `req`: the express request object.
10- `options` *(optional)*: an object which accepts the following options:
11 - `includeOptionals`: if set to `true`, the returned value includes optional data. Defaults to `false`.
12 - `onlyValidData`: if set to `false`, the returned value includes data from fields
13 that didn't pass their validations. Defaults to `true`.
14 - `locations`: an array of locations to extract the data from. The acceptable values include
15 `body`, `cookies`, `headers`, `params` and `query`. Defaults to `undefined`, which means all locations.
16> *Returns:* an object of data that express-validator has validated or sanitized.
17
18Extracts data validated or sanitized by express-validator from the request and builds
19an object with them. Nested paths and wildcards are properly handled as well.
20See examples below.
21
22## Examples
23### Gathering data from multiple locations
24If data you validated or sanitized is spread across various request locations
25(e.g. `req.body`, `req.query`, `req.params`, etc), then `matchedData` will gather it properly.
26You can also customize which locations you want the data from.
27
28```js
29// Suppose the request looks like this:
30// req.query = { from: '2017-01-12' }
31// req.body = { to: '2017-31-12' }
32
33app.post('/room-availability', check(['from', 'to']).isISO8601(), (req, res, next) => {
34 const queryData = matchedData(req, { locations: ['query'] });
35 const bodyData = matchedData(req, { locations: ['body'] });
36 const allData = matchedData(req);
37 console.log(queryData); // { from: '2017-01-12' }
38 console.log(bodyData); // { to: '2017-31-12' }
39 console.log(allData); // { from: '2017-01-12', to: '2017-31-12' }
40});
41```
42
43### Including optional data
44You may want to have [optional values](api-validation-chain.md#optionaloptions) among the required ones.
45
46If they are not included, some databases might understand that you don't to update that value,
47so it's useful to set them to `null` or an empty string.
48
49```js
50// Suppose the request looks like this:
51// req.body = { name: 'John Doe', bio: '' }
52
53app.post('/update-user', [
54 check('name').not().isEmpty(),
55 check('bio').optional({ checkFalsy: true }).escape(),
56], (req, res, next) => {
57 const requiredData = matchedData(req, { includeOptionals: false });
58 const allData = matchedData(req, { includeOptionals: true });
59 console.log(requiredData); // { name: 'John Doe' }
60 console.log(allData); // { name: 'John Doe', bio: '' }
61});
62```
\No newline at end of file