-
Notifications
You must be signed in to change notification settings - Fork 320
/
index.js
61 lines (55 loc) · 2.2 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
const { body, validationResult } = require('express-validator/check')
const { formatValidationErrors } = require('../../../utils.js')
module.exports = (app) => {
app.post(
'/full-page-examples/passport-details',
[
body('passport-number')
.exists()
.not().isEmpty().withMessage('Enter your passport number'),
body('expiry')
.exists()
.not().isEmpty().withMessage('Enter your expiry day'),
body('expiry-month')
.exists()
.not().isEmpty().withMessage('Enter your expiry month'),
body('expiry-year')
.exists()
.not().isEmpty().withMessage('Enter your expiry year')
],
(request, response) => {
const errors = formatValidationErrors(validationResult(request))
if (!errors) {
return response.render('./full-page-examples/passport-details/confirm')
}
// If any of the date inputs error apply a general error.
const expiryNamePrefix = 'expiry'
const expiryErrors = Object.values(errors).filter(error => error.id.includes(expiryNamePrefix + '-'))
if (expiryErrors) {
const firstExpiryErrorId = expiryErrors[0].id
// Get the first error message and merge it into a single error message.
errors[expiryNamePrefix] = {
id: expiryNamePrefix,
href: '#' + firstExpiryErrorId
}
// Construct a single error message based on all three error messages.
errors[expiryNamePrefix].text = 'Enter your expiry '
if (expiryErrors.length === 3) {
errors[expiryNamePrefix].text += 'date'
} else {
errors[expiryNamePrefix].text += expiryErrors.map(error => error.text.replace('Enter your expiry ', '')).join(' and ')
}
}
let errorSummary = Object.values(errors)
if (expiryErrors) {
// Remove all other errors from the summary so we only have one message that links to the expiry input.
errorSummary = errorSummary.filter(error => !error.id.includes(expiryNamePrefix + '-'))
}
response.render('./full-page-examples/passport-details/index', {
errors,
errorSummary,
values: request.body // In production this should sanitized.
})
}
)
}