Skip to content

Commit

Permalink
5.3.1
Browse files Browse the repository at this point in the history
  • Loading branch information
gustavohenke committed Dec 23, 2018
1 parent 42689b5 commit 58013ad
Show file tree
Hide file tree
Showing 5 changed files with 222 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 @@ -6,7 +6,7 @@
"Rusty Bailey <rustylbailey@gmail.com>",
"Gustavo Henke <guhenke@gmail.com>"
],
"version": "5.3.0",
"version": "5.3.1",
"homepage": "https://express-validator.github.io",
"license": "MIT",
"repository": {
Expand Down
117 changes: 117 additions & 0 deletions website/versioned_docs/version-5.3.1/api-check.md
@@ -0,0 +1,117 @@
---
id: version-5.3.1-check-api
title: check API
original_id: check-api
---

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

## `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-dynamic-messages.md).
> *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/check');
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(422).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:

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

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

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

## `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/check');
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)
```
102 changes: 102 additions & 0 deletions website/versioned_docs/version-5.3.1/feature-error-messages.md
@@ -0,0 +1,102 @@
---
id: version-5.3.1-custom-error-messages
title: Custom Error Messages
original_id: custom-error-messages
---

express-validator's default error message is a simple `Invalid value`.
That's enough to cover all fields without being too opinionated.

You can, however, specify meaningful error messages in a variety of ways.

## Error message levels
### Validator Level
When you want fine grained control over the error message of each validator,
you may specify them using the [`.withMessage()` method](api-validation-chain.md#withmessagemessage).

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

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

In the example above, if the password is less than 5 characters long, an error with the message
`must be at least 5 chars long` will be reported.
If it also doesn't contain a number, then an error with the message `must contain a number` will be
reported.

### Custom Validator Level
If you're using a custom validator, then it may very well throw or reject promises to indicate an invalid value.
In these cases, the error gets reported with a message that's equal to what was thrown by the validator:

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

app.post('/user', [
check('email').custom(value => {
return User.findByEmail(value).then(user => {
if (user) {
return Promise.reject('E-mail already in use');
}
});
}),
check('password').custom((value, { req }) => {
if (value !== req.body.passwordConfirmation) {
throw new Error('Password confirmation is incorrect');
}
})
], (req, res) => {
// Handle the request somehow
});
```

### Field Level
Messages can be specified at the field level by using the second parameter of the
[validation chain creators](api-check.md#check-field-message).

Theses messages are used as fall backs when a validator doesn't specify its own message:

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

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')
.isLength({ min: 5 })
.matches(/\d/)
], (req, res) => {
// Handle the request somehow
});
```

In the example above, when the `password` field is shorter than 5 characters, or doesn't contain a number,
it will be reported with the message `The password must be 5+ chars long and contain a number`,
as these validators didn't specify a message of their own.

## Dynamic messages

You can build dynamic validation messages by providing functions anywhere a validation message is supported.
This is specially useful if you use a translation library to provide tailored messages:

```js
// check(field, withMessage) and .withMessage() work the same
check('something').isInt().withMessage((value, { req, location, path }) => {
return req.translate('validation.message.path', { value, location, path });
}),
check('somethingElse', (value, { req, location, path }) => {
return req.translate('validation.message.path', { value, location, path });
}),

// oneOf is special though - it only receives the req object for now
oneOf([ someValidation, anotherValidation ], ({ req }) => {
return req.translate('validation.multiple_failures');
});
```
1 change: 1 addition & 0 deletions website/versions.json
@@ -1,4 +1,5 @@
[
"5.3.1",
"5.3.0",
"5.2.0"
]

0 comments on commit 58013ad

Please sign in to comment.