-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathEmailAddressField.ts
More file actions
89 lines (75 loc) · 2.42 KB
/
EmailAddressField.ts
File metadata and controls
89 lines (75 loc) · 2.42 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import {
preventUnicodeInEmail,
type EmailAddressFieldComponent
} from '@defra/forms-model'
import joi, { type CustomHelpers } from 'joi'
import { FormComponent } from '~/src/server/plugins/engine/components/FormComponent.js'
import { messageTemplate } from '~/src/server/plugins/engine/pageControllers/validationOptions.js'
import {
type ErrorMessageTemplateList,
type FormPayload,
type FormSubmissionError
} from '~/src/server/plugins/engine/types.js'
export class EmailAddressField extends FormComponent {
declare options: EmailAddressFieldComponent['options']
constructor(
def: EmailAddressFieldComponent,
props: ConstructorParameters<typeof FormComponent>[1]
) {
super(def, props)
const { options } = def
let formSchema = joi
.string()
.trim()
.email()
.custom((value, helpers: CustomHelpers<string>) =>
preventUnicodeInEmail(value, helpers)
)
.label(this.label)
.required()
if (options.required === false) {
formSchema = formSchema.allow('')
}
if (options.customValidationMessage) {
const message = options.customValidationMessage
formSchema = formSchema.messages({
'any.required': message,
'string.empty': message,
'string.email': message
})
} else if (options.customValidationMessages) {
formSchema = formSchema.messages(options.customValidationMessages)
}
this.formSchema = formSchema.default('')
this.stateSchema = formSchema.default(null).allow(null)
this.options = options
}
getViewModel(payload: FormPayload, errors?: FormSubmissionError[]) {
const viewModel = super.getViewModel(payload, errors)
const { attributes } = viewModel
attributes.autocomplete = 'email'
return {
...viewModel,
type: 'email'
}
}
/**
* For error preview page that shows all possible errors on a component
*/
getAllPossibleErrors(): ErrorMessageTemplateList {
return EmailAddressField.getAllPossibleErrors()
}
/**
* Static version of getAllPossibleErrors that doesn't require a component instance.
*/
static getAllPossibleErrors(): ErrorMessageTemplateList {
return {
baseErrors: [
{ type: 'required', template: messageTemplate.required },
{ type: 'format', template: messageTemplate.format },
{ type: 'unicode', template: messageTemplate.unicode }
],
advancedSettingsErrors: []
}
}
}