1 | ---
|
2 | id: wildcards
|
3 | title: Wildcards
|
4 | ---
|
5 |
|
6 | Sometimes you will want to apply the same rules to all items of an array or all keys of some object.
|
7 | That's what the `*` character - also known as a wildcard -- is for.
|
8 |
|
9 | For example, imagine you want to validate that all addresses have a valid postal code,
|
10 | and that the number of each address is sanitized as an integer number.
|
11 |
|
12 | We can do this with the following code:
|
13 |
|
14 | ```js
|
15 | const express = require('express');
|
16 | const { check, sanitize } = require('express-validator');
|
17 |
|
18 | const app = express();
|
19 | app.use(express.json());
|
20 |
|
21 | app.post('/addresses', [
|
22 | check('addresses.*.postalCode').isPostalCode(),
|
23 | sanitize('addresses.*.number').toInt()
|
24 | ], (req, res) => {
|
25 | // Handle the request
|
26 | });
|
27 | ```
|
28 |
|
29 | This 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 |