-
Notifications
You must be signed in to change notification settings - Fork 0
/
customValidator.ts
90 lines (74 loc) · 2.46 KB
/
customValidator.ts
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
90
import {
IErrorHandlerBaseOptions,
IErrorHandlerOptions,
IValidationInstanceOptions,
Validation,
} from '../src/validation';
import {
RequiredValidator,
ValidatorInterface,
} from '../src/validation/validators';
const form = document.querySelector('form');
if (!form) {
throw new Error('No form');
}
// avoid submitting form for demo purposes
form.addEventListener('submit', e => {
e.preventDefault();
});
// create custom validator
const DigitSum: ValidatorInterface<{expected: number, actual: number}> = {
getIdentifier: () => 'digitsum',
/**
* Checks whether the respective input should be validated with this validator
*/
isApplicable: input => {
// we want a data-sum value to be numeric and > 0
if (!input.hasAttribute('data-sum')) return false;
const sum = Number.parseInt(input.getAttribute('data-sum') ?? '');
if (Number.isNaN(sum) || sum <= 0) return false;
return true;
},
/**
* Given callbacks for validation error and success, the validation function
* determines which callback to call
*/
validate: input => (onError, onSuccess) => {
const value = input.value;
if (value.length === 0)
return onSuccess();
const target = Number.parseInt(input.getAttribute('data-sum') ?? '');
const digits = value.split('').filter(c => /\d/.test(c)).map(Number);
const sum = digits.reduce((s, d) => s + d, 0);
if (target === sum)
return onSuccess();
// fill the args passed to the validation message function
return onError({
expected: target,
actual: sum,
});
},
/**
* Generate a validation message.
* This could use the translated labels. See existing validators for references
*/
getValidationMessage: (label, args) =>
`${label} should contain digits with sum ${args.expected}, was ${args.actual}`,
};
const validation = new Validation<IValidationInstanceOptions, IErrorHandlerBaseOptions & Partial<IErrorHandlerOptions>>();
// configure validators
validation
.registerValidator(RequiredValidator)
// add our custom validator
.registerValidator(DigitSum);
validation.init(form, {
errorHandlerOptions: {
labels: {
errorListTitle: 'Please correct the following errors in the form:',
},
translations: {
validationMessages: {
},
},
},
});