Skip to content

Commit

Permalink
6.4.1
Browse files Browse the repository at this point in the history
  • Loading branch information
gustavohenke committed May 1, 2020
1 parent 70af46e commit 29374cb
Show file tree
Hide file tree
Showing 11 changed files with 543 additions and 3 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
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"Rusty Bailey <[email protected]>",
"Gustavo Henke <[email protected]>"
],
"version": "6.4.0",
"version": "6.4.1",
"homepage": "https://express-validator.github.io",
"license": "MIT",
"repository": {
Expand Down
29 changes: 28 additions & 1 deletion website/i18n/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,33 @@
},
"version-6.4.0/version-6.4.0-sanitization-chain-api": {
"title": "Sanitization Chain API"
},
"version-6.4.0/version-6.4.0-custom-validators-sanitizers": {
"title": "Custom validators/sanitizers"
},
"version-6.4.0/version-6.4.0-sanitization": {
"title": "Sanitization"
},
"version-6.4.1/version-6.4.1-matched-data-api": {
"title": "matchedData()"
},
"version-6.4.1/version-6.4.1-validation-result-api": {
"title": "validationResult()"
},
"version-6.4.1/version-6.4.1-custom-validators-sanitizers": {
"title": "Custom validators/sanitizers"
},
"version-6.4.1/version-6.4.1-custom-error-messages": {
"title": "Custom Error Messages"
},
"version-6.4.1/version-6.4.1-schema-validation": {
"title": "Schema Validation"
},
"version-6.4.1/version-6.4.1-whole-body-validation": {
"title": "Whole Body Validation"
},
"version-6.4.1/version-6.4.1-wildcards": {
"title": "Wildcards"
}
},
"links": {
Expand All @@ -184,4 +211,4 @@
"Edit this Doc|recruitment message asking to edit the doc source": "Edit",
"Translate this Doc|recruitment message asking to translate the docs": "Translate"
}
}
}
63 changes: 63 additions & 0 deletions website/versioned_docs/version-6.4.1/api-matched-data.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
---
id: version-6.4.1-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.

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

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

```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: '' }
});
```
121 changes: 121 additions & 0 deletions website/versioned_docs/version-6.4.1/api-validation-result.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
---
id: version-6.4.1-validation-result-api
title: validationResult()
original_id: validation-result-api
---

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

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

Each error returned by [`.array()`](#array-options) and [`.mapped()`](#mapped) methods
has the following format _by default_:

```js
{
"msg": "The error message",
"param": "param.name.with.index[0]",
"value": "param value",
// Location of the param that generated this error.
// It's either body, query, params, cookies or headers.
"location": "body",

// nestedErrors only exist when using the oneOf function
"nestedErrors": [{ ... }]
}
```


### `.withDefaults(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
[`Result`](#result) instance.

Below is an example which sets a default error formatter:

```js
const { validationResult } = require('express-validator');

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

app.post('/create-user', yourValidationChains, (req, res) => {
// errors will be like [{ myLocation: 'body' }, { myLocation: 'query' }], etc
const errors = myValidationResult(req).array();
});
```

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

### `.isEmpty()`
> *Returns:* a boolean indicating whether this result object contains no errors at all.
```js
app.post('/create-user', yourValidationChains, (req, res) => {
const result = validationResult(req);
const hasErrors = !result.isEmpty();
// do something if hasErrors is true
});
```

### `.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
```js
app.post('/create-user', yourValidationChains, (req, res, next) => {
const errorFormatter = ({ location, msg, param, value, nestedErrors }) => {
// Build your resulting errors however you want! String, object, whatever - it works!
return `${location}[${param}]: ${msg}`;
};
const result = validationResult(req).formatWith(errorFormatter);
if (!result.isEmpty()) {
// Response will contain something like
// { errors: [ "body[password]: must be at least 10 chars long" ] }
return res.json({ errors: result.array() });
}

// Handle your request as if no errors happened
});
```

### `.array([options])`
- `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.

If the option `onlyFirstError` is set to `true`, then only the first
error for each field will be included.

### `.mapped()`
> *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
decorated with the same validation result API.

```js
try {
validationResult(req).throw();
// Oh look at ma' success! All validations passed!
} catch (err) {
console.log(err.mapped()); // Oh noes!
}
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
---
id: version-6.4.1-custom-validators-sanitizers
title: Custom validators/sanitizers
original_id: custom-validators-sanitizers
---

Although express-validator offers plenty of handy validators and sanitizers through its underlying
dependency [validator.js](https://github.com/chriso/validator.js), it doesn't always suffice when
building your application.

For these cases, you may consider writing a custom validator or a custom sanitizer.

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

Custom validators may return Promises to indicate an async validation (which will be awaited upon),
or `throw` any value/reject a promise to [use a custom error message](feature-error-messages.md#custom-validator-level).

> **Note:** if your custom validator returns a promise, it must reject to indicate that the field is invalid.
### 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
});
```

### 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
});
```

## Custom sanitizers
Custom sanitizers can be implemented by using the method `.customSanitizer()`, no matter if
the [validation chain one](api-validation-chain.md#customsanitizersanitizer) or
the [sanitization chain one](api-sanitization-chain.md#customsanitizersanitizer).
Just like with the validators, you specify the sanitizer function, which _must_ be synchronous at the
moment.

### 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
});
```

0 comments on commit 29374cb

Please sign in to comment.