UNPKG

1.12 kBMarkdownView Raw
1---
2id: wildcards
3title: Wildcards
4---
5
6Sometimes you will want to apply the same rules to all items of an array or all keys of some object.
7That's what the `*` character - also known as a wildcard -- is for.
8
9For example, imagine you want to validate that all addresses have a valid postal code,
10and that the number of each address is sanitized as an integer number.
11
12We can do this with the following code:
13
14```js
15const express = require('express');
16const { check, sanitize } = require('express-validator');
17
18const app = express();
19app.use(express.json());
20
21app.post('/addresses', [
22 check('addresses.*.postalCode').isPostalCode(),
23 sanitize('addresses.*.number').toInt()
24], (req, res) => {
25 // Handle the request
26});
27```
28
29This will handle cases where you send an array of addresses:
30```json
31{
32 "addresses": [
33 { "postalCode": "2010", "number": "500" },
34 { "postalCode": "", "number": "501" },
35 ]
36}
37```
38
39...or even cases where you want a predefined set of addresses:
40```json
41{
42 "addresses": {
43 "home": { "postalCode": "", "number": "501" },
44 "work": { "postalCode": "2010", "number": "500" }
45 }
46}
47```
\No newline at end of file