-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathValidator.ts
306 lines (257 loc) · 8.02 KB
/
Validator.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
import {
createIntl,
createIntlCache,
IntlCache,
IntlShape
} from '@formatjs/intl';
import { Rule, RuleFunction, RuleObject } from './Rule';
import { RuleOptions } from './RuleOptions';
import { ValidatorArea } from './components/ValidatorArea';
import required from './rules/required';
import { getValue, isCanvasElement } from './common/dom';
import { LocaleMessagesMap } from './LocaleMessages';
import { capitalize } from './common/utils';
import en from './locale/en';
export class Validator {
public static VALIDATABLE_ELEMENTS: string[] = [
'canvas', 'input', 'meter', 'select', 'textarea', 'output', 'progress'
];
/**
* Map containing the rule object belonging to a rule string
*/
public static rules: Record<string, Rule> = {
required
};
/**
* The elements to be validated
*/
private readonly elements: HTMLElement[];
/**
* The rules to validate the elements with
*/
private readonly validationRules: RuleOptions;
/**
* Validation errors when elements are invalid
*/
private errors: string[] = [];
/**
* Name used to specify error messages
*/
private readonly name: string | null;
/**
* Intl cache to prevent memory leaks
*/
private readonly intlCache: IntlCache;
/**
* Intl constructor to localize messages
*/
private intl: IntlShape<string>;
/**
* Validator area used to access other areas and the provider
*/
private area?: ValidatorArea;
/**
* Name used to overwrite name attribute, to allow messages to be more specific
*/
private validationName?: string;
/**
* The active locale
*/
private static locale = 'en';
/**
* Map with messages keyed with locales, containing EN as default
*/
private static messages: LocaleMessagesMap = en;
public constructor(
elements: HTMLElement[],
rules: RuleOptions,
name: string | null,
validationName?: string
) {
this.elements = elements;
this.validationRules = rules;
this.name = name;
this.validationName = validationName;
this.intlCache = createIntlCache();
this.intl = this.createIntl();
}
/**
* Creates a new intl instance
*/
private createIntl(): IntlShape<string> {
return createIntl({
locale: Validator.locale,
messages: Validator.messages[Validator.locale]
}, this.intlCache);
}
/**
* Get the rule list as array
*/
private getRuleList(): string[] {
if (typeof this.validationRules === 'string') {
return this.validationRules.split('|');
}
return this.validationRules;
}
public hasRule(rule: string): boolean {
return this.getRuleList().indexOf(rule) !== -1;
}
/**
* Validate the elements
*/
public async validate(): Promise<boolean> {
this.errors = [];
if (this.hasValidatableElements()) {
return !(await Promise.all(this.getRuleList().map((rule: string) => this.validateRule(rule))))
.filter((passed: boolean) => !passed)
.length;
}
return true;
}
/**
* Indicated whether a given rule name is a rule function
*/
private static isRuleFunction(rule: string): boolean {
return typeof Validator.rules[rule] === 'function';
}
/**
* Get the rule name and the parameters as tuple
*/
private static getRuleNameAndParameters(rule: string): [string, string[]] {
const [name, ...splittedParameters] = rule.split(':');
const parameters = splittedParameters.join(':');
if (['regex'].indexOf(name) !== -1) {
return [name, [parameters]];
}
return [name, parameters.split(',')];
}
/**
* Validate a specific rule
*/
private async validateRule(rule: string): Promise<boolean> {
const [ruleName, ruleParameters] = Validator.getRuleNameAndParameters(rule);
if (Validator.ruleExists(ruleName)) {
const ruleObj: RuleObject = Validator.isRuleFunction(ruleName)
? (Validator.rules[ruleName] as RuleFunction)(this)
: Validator.rules[ruleName] as RuleObject;
const passed = await ruleObj.passed(this.elements, ...ruleParameters);
if(!passed) {
this.errors.push(this.localize(ruleObj.message(), ...ruleParameters));
return false;
}
return true;
}
throw new Error(`Validation rule ${rule} not found.`);
}
public hasValidatableElements(): boolean {
return this.elements.some((element: HTMLElement) => this.shouldValidate(element));
}
public shouldValidate(element: HTMLElement): boolean {
if (this.hasRule('required')) {
return true;
}
return !!(getValue(element).length
|| isCanvasElement(element)
);
}
/*
* Get the capitalized, localized message
*/
public localize(message: string, ...ruleArgs: string[]): string {
return capitalize(this.intl.formatMessage({
id: message,
defaultMessage: message
}, {
name: this.validationName || this.name,
...ruleArgs
}));
}
/**
* Get all the errors
*/
public getErrors(): string[] {
return this.errors;
}
/**
* Sets the current area
*/
public setArea(area: ValidatorArea): Validator {
this.area = area;
return this;
}
/**
* Gets the area where this validator instance is used
*/
public getArea(): ValidatorArea {
if (this.area) {
return this.area;
}
throw new Error('Areas are only available when validating React components.');
}
/**
* Gets a list of validation element refs, optionally specified by area name
*/
public refs(name?: string, type?: typeof HTMLElement): HTMLElement[] {
return this.getArea().context.getRefs(name, type);
}
/**
* Merges rules from different sources into one array
*/
public static mergeRules(...rules: RuleOptions[]): string[] {
let mergedRules: string[] = [];
rules.forEach((rule: string | string[]) => {
if (typeof rule === 'string') {
rule.split('|').forEach((subRule) => mergedRules.push(subRule));
} else if (Array.isArray(rule) && rule.length) {
mergedRules = [...mergedRules, ...rule];
}
});
return mergedRules;
}
/**
* Extend the validator with a new rule
*/
public static extend(name: string, rule: Rule): void {
Validator.rules[name] = rule;
}
/**
* Check whether the validator has a rule
*/
public static ruleExists(name: string): boolean {
return Object.prototype.hasOwnProperty.call(Validator.rules, name);
}
public static hasLocale(locale: string): boolean {
return !!Object.prototype.hasOwnProperty.call(Validator.messages, locale);
}
/**
* Adds a locale map to the messages map, keyed by locale
*/
public static addLocale(messages: LocaleMessagesMap): void {
Validator.messages = {
...Validator.messages,
...messages
};
}
/**
* Sets the given locale for all the new created validator instance or defaults to English if the locale does not
* exist
*/
public static setLocale(locale: string, messages?: LocaleMessagesMap): void {
if (!messages) {
if (Validator.hasLocale(locale)) {
Validator.locale = locale;
} else {
Validator.locale = 'en';
}
} else {
Validator.addLocale(messages);
Validator.setLocale(locale);
}
}
/**
* Gets the current locale of the validator
*/
public static getLocale(): string {
return Validator.locale;
}
}