1 | ---
|
2 | id: validation-result-api
|
3 | title: validationResult()
|
4 | ---
|
5 |
|
6 | These methods are all available via `require('express-validator')`.
|
7 |
|
8 | ## `validationResult(req)`
|
9 | - `req`: the express request object
|
10 | > *Returns:* a [`Result`](#result) object
|
11 |
|
12 | Extracts the validation errors from a request and makes them available in a [`Result`](#result) object.
|
13 |
|
14 | Each error returned by [`.array()`](#array-options) and [`.mapped()`](#mapped) methods
|
15 | have the following format _by default_:
|
16 |
|
17 | ```js
|
18 | {
|
19 | "msg": "The error message",
|
20 | "param": "param.name.with.index[0]",
|
21 | "value": "param value",
|
22 | // Location of the param that generated this error.
|
23 | // It's either body, query, params, cookies or headers.
|
24 | "location": "body",
|
25 |
|
26 | // nestedErrors only exist when using the oneOf function
|
27 | "nestedErrors": [{ ... }]
|
28 | }
|
29 | ```
|
30 |
|
31 |
|
32 | ### `.withDefaults(options)`
|
33 | - `options` *(optional)*: an object of options. Defaults to `{ formatter: error => error }`
|
34 | > *Returns:* a new [`validationResult`](#validationresultreq) function, using the provided options
|
35 |
|
36 | Creates a new `validationResult()`-like function with default options passed to the generated
|
37 | [`Result`](#result) instance.
|
38 |
|
39 | Below is an example which sets a default error formatter:
|
40 |
|
41 | ```js
|
42 | const { validationResult } = require('express-validator');
|
43 |
|
44 | const myValidationResult = validationResult.withDefaults({
|
45 | formatter: (error) => {
|
46 | return {
|
47 | myLocation: error.location,
|
48 | };
|
49 | }
|
50 | });
|
51 |
|
52 | app.post('/create-user', yourValidationChains, (req, res) => {
|
53 | // errors will be like [{ myLocation: 'body' }, { myLocation: 'query' }], etc
|
54 | const errors = myValidationResult(req).array();
|
55 | });
|
56 | ```
|
57 |
|
58 | ## `Result`
|
59 | An object that holds the current state of validation errors in a request and allows access to it in
|
60 | a variety of ways.
|
61 |
|
62 | ### `.isEmpty()`
|
63 | > *Returns:* a boolean indicating whether this result object contains no errors at all.
|
64 |
|
65 | ```js
|
66 | app.post('/create-user', yourValidationChains, (req, res) => {
|
67 | const result = validationResult(req);
|
68 | const hasErrors = !result.isEmpty();
|
69 | // do something if hasErrors is true
|
70 | });
|
71 | ```
|
72 |
|
73 | ### `.formatWith(formatter)`
|
74 | - `formatter(error)`: the function to use to format when returning errors.
|
75 | The `error` argument is an object in the format of `{ location, msg, param, value, nestedErrors }`, as described above.
|
76 | > *Returns:* a new `Result` instance
|
77 |
|
78 | ```js
|
79 | app.post('/create-user', yourValidationChains, (req, res, next) => {
|
80 | const errorFormatter = ({ location, msg, param, value, nestedErrors }) => {
|
81 | // Build your resulting errors however you want! String, object, whatever - it works!
|
82 | return `${location}[${param}]: ${msg}`;
|
83 | };
|
84 | const result = validationResult(req).formatWith(errorFormatter);
|
85 | if (!result.isEmpty()) {
|
86 | // Response will contain something like
|
87 | // { errors: [ "body[password]: must be at least 10 chars long" ] }
|
88 | return res.json({ errors: result.array() });
|
89 | }
|
90 |
|
91 | // Handle your request as if no errors happened
|
92 | });
|
93 | ```
|
94 |
|
95 | ### `.array([options])`
|
96 | - `options` *(optional)*: an object of options. Defaults to `{ onlyFirstError: false }`
|
97 | > *Returns:* an array of validation errors.
|
98 |
|
99 | Gets all validation errors contained in this result object.
|
100 |
|
101 | If the option `onlyFirstError` is set to `true`, then only the first
|
102 | error for each field will be included.
|
103 |
|
104 | ### `.mapped()`
|
105 | > *Returns:* an object where the keys are the field names, and the values are the validation errors
|
106 |
|
107 | Gets the first validation error of each failed field in the form of an object.
|
108 |
|
109 | ### `.throw()`
|
110 | If this result object has errors, then this method will throw an exception
|
111 | decorated with the same validation result API.
|
112 |
|
113 | ```js
|
114 | try {
|
115 | validationResult(req).throw();
|
116 | // Oh look at ma' success! All validations passed!
|
117 | } catch (err) {
|
118 | console.log(err.mapped()); // Oh noes!
|
119 | }
|
120 | ```
|