Skip to content

Commit

Permalink
6.13.0
Browse files Browse the repository at this point in the history
  • Loading branch information
fedeci committed Oct 12, 2021
1 parent 75f1457 commit 5651810
Show file tree
Hide file tree
Showing 6 changed files with 233 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.12.2",
"version": "6.13.0",
"homepage": "https://express-validator.github.io",
"license": "MIT",
"repository": {
Expand Down
6 changes: 6 additions & 0 deletions website/i18n/en.json
Expand Up @@ -200,6 +200,12 @@
"version-6.12.1/version-6.12.1-running-imperatively": {
"title": "Running validations imperatively"
},
"version-6.13.0/version-6.13.0-custom-validators-sanitizers": {
"title": "Custom validators/sanitizers"
},
"version-6.13.0/version-6.13.0-schema-validation": {
"title": "Schema Validation"
},
"version-6.2.0/version-6.2.0-validation-chain-api": {
"title": "Validation Chain API"
},
Expand Down
@@ -0,0 +1,131 @@
---
id: version-6.13.0-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/validatorjs/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

<!--DOCUSAURUS_CODE_TABS-->
<!--JavaScript-->

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

<!--TypeScript-->

```js
import { body, CustomValidator } from 'express-validator';
// This allows you to reuse the validator
const isValidUser: CustomValidator = value => {
return User.findUserByEmail(value).then(user => {
if (user) {
return Promise.reject('E-mail already in use');
}
});
};

app.post('/user', body('email').custom(isValidUser), (req, res) => {
// Handle the request
});
```

<!--END_DOCUSAURUS_CODE_TABS-->

> **Note:** In the example above, validation might fail even due to issues with fetching User information. The implications of accessing the data layer during validation should be carefully considered.
### Example: checking if password confirmation matches password

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

app.post(
'/user',
body('password').isLength({ min: 5 }),
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

<!--DOCUSAURUS_CODE_TABS-->
<!--JavaScript-->

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

app.post(
'/object/:id',
param('id').customSanitizer(value => {
return ObjectId(value);
}),
(req, res) => {
// Handle the request
},
);
```

<!--TypeScript-->

```typescript
import { param } from 'express-validator';
// This allows you to reuse the validator
const toObjectId: CustomSanitizer = value => {
return ObjectId(value);
};

app.post('/object/:id', param('id').customSanitizer(toObjectId), (req, res) => {
// Handle the request
});
```

<!--END_DOCUSAURUS_CODE_TABS-->
93 changes: 93 additions & 0 deletions website/versioned_docs/version-6.13.0/feature-schema-validation.md
@@ -0,0 +1,93 @@
---
id: version-6.13.0-schema-validation
title: Schema Validation
original_id: schema-validation
---

Schemas are a special, object-based way of defining validations or sanitizations on requests.
At the root-level, you specify field paths as keys, and objects as values -- which define
the error messages, locations and validations/sanitizations.

Its syntax looks like this:

```js
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;
},
},
// and sanitizers
customSanitizer: {
options: (value, { req, location, path }) => {
let sanitizedValue;

if (req.body.foo && location && path) {
sanitizedValue = parseInt(value);
} else {
sanitizedValue = 0;
}

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,
},
rtrim: {
// Options as an array
options: [[' ', '-']],
},
},
// Support bail functionality in schemas
email: {
isEmail: {
bail: true,
},
},
// Support if functionality in schemas
someField: {
isInt: {
if: value => {
return value !== '';
},
},
},
// Wildcards/dots for nested fields work as well
'addresses.*.postalCode': {
// Make this field optional when undefined or null
optional: { options: { nullable: true } },
isPostalCode: {
options: 'US', // set postalCode locale here
},
},
}),
(req, res, next) => {
// handle the request as usual
},
);
```
1 change: 1 addition & 0 deletions website/versions.json
@@ -1,4 +1,5 @@
[
"6.13.0",
"6.12.2",
"6.12.1",
"6.12.0",
Expand Down

0 comments on commit 5651810

Please sign in to comment.