/
validator.ts
1693 lines (1413 loc) · 63.9 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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Serenity validator implementation inspired from:
* jQuery Validation Plugin, https://jqueryvalidation.org/)
* - and -
* https://raw.githubusercontent.com/haacked/aspnet-client-validation
*/
import { Config } from "./config";
import { Fluent } from "./fluent";
import { parseDate, parseDecimal, parseInteger, stringFormat } from "./formatting";
import { localText } from "./localtext";
import { isArrayLike } from "./system";
/**
* An `HTMLElement` that can be validated (`input`, `select`, `textarea`, or [contenteditable).
*/
export interface ValidatableElement extends HTMLElement {
form?: HTMLFormElement;
name?: string;
type?: string;
value?: string;
}
export type ValidationValue = string | string[] | number | boolean;
/**
* Validation plugin signature with multitype return.
* Boolean return signifies the validation result, which uses the default validation error message read from the element attribute.
* String return signifies failed validation, which then will be used as the validation error message.
* Promise return signifies asynchronous plugin behavior, with same behavior as Boolean or String.
*/
export type ValidationProvider = (value: ValidationValue, element: ValidatableElement, params?: any) => boolean | string | Promise<boolean | string>;
export interface ValidationErrorMap {
[name: string]: (string | boolean);
}
export interface ValidationErrorItem {
message: string;
element: ValidatableElement;
method?: string;
}
export type ValidationErrorList = ValidationErrorItem[];
export type ValidationRules = Record<string, any>;
export interface ValidationRulesMap {
[name: string]: ValidationRules;
}
export type ValidateEventDelegate = (element: ValidatableElement, event: Event, validator: Validator) => void;
function messageKey(method: string) {
return "msg" + method.charAt(0).toUpperCase() + method.substring(1).toLowerCase()
}
export interface ValidatorOptions {
/** True for logging debug info */
debug?: boolean;
/**
* Use this class to create error labels, to look for existing error labels and to add it to invalid elements.
*
* default: "error"
*/
errorClass?: string | undefined;
/**
* Use this element type to create error messages and to look for existing error messages. The default, "label",
* has the advantage of creating a meaningful link between error message and invalid field using the for attribute (which is always used, regardless of element type).
*
* default: "label"
*/
errorElement?: string | undefined;
/**
* Customize placement of created error labels. First argument: The created error label. Second argument: The invalid element.
*
* default: Places the error label after the invalid element
*/
errorPlacement?(error: HTMLElement, element: ValidatableElement, validator: Validator): void;
/**
* Focus the last active or first invalid element on submit via validator.focusInvalid(). The last active element is the one
* that had focus when the form was submitted, avoiding stealing its focus. If there was no element focused, the first one
* in the form gets it, unless this option is turned off.
*
* default: true
*/
focusInvalid?: boolean | undefined;
/**
* How to highlight invalid fields. Override to decide which fields and how to highlight.
*
* default: Adds errorClass (see the option) to the element
*/
highlight?(element: ValidatableElement, errorClass: string, validClass: string): void;
/**
* Elements to ignore when validating, simply filtering them out. CSS not-method is used, therefore everything that is
* accepted by not() can be passed as this option. Inputs of type submit and reset are always ignored, so are disabled elements.
*/
ignore?: string | undefined;
/**
* Callback for custom code when an invalid form is submitted. Called with an event object as the first argument, and the validator
* as in the second.
*/
invalidHandler?(event: Event, validator: Validator): void;
/**
* Key/value pairs defining custom messages. Key is the name of an element, value the message to display for that element. Instead
* of a plain message, another map with specific messages for each rule can be used. Overrides the title attribute of an element or
* the default message for the method (in that order). Each message can be a String or a Callback. The callback is called in the scope
* of the validator, with the rule's parameters as the first argument and the element as the second, and must return a String to display
* as the message.
*
* default: the default message for the method used
*/
messages?: Record<string, string> | undefined;
normalizer?: (val: ValidationValue, element: ValidatableElement) => string;
/**
* Boolean or Function. Validate checkboxes and radio buttons on click. Set to false to disable.
*
* Set to a Function to decide for yourself when to run validation.
* A boolean true is not a valid value.
*/
onclick?: ValidateEventDelegate | boolean | undefined;
/**
* Function. Validate elements when user focuses in. If omitted hides all other fields marked as invalid.
*
* Set to a custom Function to decide for yourself when to run validation.
*/
onfocusin?: ValidateEventDelegate | undefined;
/**
* Boolean or Function. Validate elements (except checkboxes/radio buttons) on blur. If nothing is entered, all rules are skipped, except when the field was already marked as invalid.
*
* Set to a Function to decide for yourself when to run validation.
* A boolean true is not a valid value.
*/
onfocusout?: ValidateEventDelegate | undefined;
/**
* Boolean or Function. Validate elements on keyup. As long as the field is not marked as invalid, nothing happens.
* Otherwise, all rules are checked on each key up event. Set to false to disable.
*
* Set to a Function to decide for yourself when to run validation.
* A boolean true is not a valid value.
*/
onkeyup?: ValidateEventDelegate | undefined;
/**
* Validate the form on submit. Set to false to use only other events for validation.
* Set to a Function to decide for yourself when to run validation.
* A boolean true is not a valid value.
*
* default: true
*/
onsubmit?: boolean | undefined;
/**
* Pending class
* default: "pending"
*/
pendingClass?: string | undefined;
/**
* A custom message display handler. Gets the map of errors as the first argument and an array of errors as the second,
* called in the context of the validator object. The arguments contain only those elements currently validated,
* which can be a single element when doing validation onblur/keyup. You can trigger (in addition to your own messages)
* the default behaviour by calling this.defaultShowErrors().
*/
rules?: ValidationRulesMap | undefined;
/**
* A custom message display handler. Gets the map of errors as the first argument and an array of errors as the second,
* called in the context of the validator object. The arguments contain only those elements currently validated, which can
* be a single element when doing validation onblur/keyup. You can trigger (in addition to your own messages) the default
* behaviour by calling this.defaultShowErrors().
*/
showErrors?(errorMap: ValidationErrorMap, errorList: ValidationErrorList, validator: Validator): void;
abortHandler?(validator: Validator): void;
/**
* Callback for handling the actual submit when the form is valid. Gets the form and the event object. Replaces the default submit.
* The right place to submit a form via Ajax after it is validated.
*/
submitHandler?(form: HTMLFormElement, event: Event, validator: Validator): void | boolean;
/**
* String or Function. If specified, the error label is displayed to show a valid element. If a String is given, it is added as
* a class to the label. If a Function is given, it is called with the label and the validated input (as a DOM element).
* The label can be used to add a text like "ok!".
*/
success?: string | ((label: HTMLElement, validatedInput: ValidatableElement) => void) | undefined;
/**
* Called to revert changes made by option highlight, same arguments as highlight.
*
* default: Removes the errorClass
*/
unhighlight?(element: ValidatableElement, errorClass: string, validClass: string, validator: Validator): void;
/**
* This class is added to an element after it was validated and considered valid.
*
* default: "valid"
*/
validClass?: string | undefined;
}
let validatorMap: WeakMap<HTMLFormElement, Validator> = new WeakMap();
function validatorEventDelegate(event: Event) {
let isContentEditable = Validator.isContentEditable(this);
// Set form expando on contenteditable
if (!this.form && isContentEditable) {
this.form = this.closest("form");
this.name = this.getAttribute("name");
}
// Ignore the element if it belongs to another form. This will happen mainly
// when setting the `form` attribute of an input to the id of another form.
//if (currentForm !== this.form) {
// return;
//}
const validator = validatorMap.get(this.form);
if (!validator)
return;
const eventType = "on" + event.type.replace(/^validate/, "");
const settings = validator.settings;
if (event.type == "focusin" && Validator.isValidatableElement(this))
validator.lastActive = this;
if (typeof (settings as any)[eventType] === "function" &&
(!settings.ignore || !(this as HTMLElement).matches(settings.ignore))) {
((settings as any)[eventType] as ValidateEventDelegate)(this, event, validator);
}
}
let customValidateRules: WeakMap<ValidatableElement, { [key: string]: ((input: ValidatableElement) => string)[] }> = new WeakMap();
export class Validator {
static optional(element: ValidatableElement) {
var val = Validator.elementValue(element);
return !Validator.methods.required(val, element) && "dependency-mismatch";
}
static autoCreateRanges: boolean = false;
static defaults: ValidatorOptions = {
messages: {},
rules: {},
errorClass: "error",
pendingClass: "pending",
validClass: "valid",
errorElement: "label",
focusInvalid: true,
onsubmit: true,
ignore: '[style*="display:none"], [style*="display: none"] *, .hidden *, input[type=hidden], .no-validate',
normalizer: function (value: string) {
return typeof value === "string" ? value.trim() : value;
},
onfocusin: function (element: ValidatableElement, event: Event, validator: Validator) {
validator.lastActive = element;
},
onfocusout: function (element: ValidatableElement, event: Event, validator: Validator) {
if (!Validator.isCheckOrRadio(element) && (element.name in validator.submitted || !Validator.optional(element))) {
validator.element(element);
}
},
onkeyup: function (element: ValidatableElement, event: KeyboardEvent, validator: Validator) {
// Avoid revalidate the field when pressing one of the following keys
var excludedKeys = ["Shift", "Control", "Alt", "CapsLock", "End", "Home",
"ArrowLeft", "ArrowUp", "ArrowRight", "ArrowDown", "Insert", "NumLock", "AltGr"];
if (event.key === "Tab" && Validator.elementValue(element) === "" || excludedKeys.includes(event.key)) {
return;
} else if (element.name in validator.submitted || element.name in validator.invalid) {
validator.element(element);
}
},
onclick: function (element: ValidatableElement, event: MouseEvent, validator: Validator) {
// Click on selects, radiobuttons and checkboxes
if (element.name in validator.submitted) {
validator.element(element);
// Or option elements, check parent select in that case
} else if ((element.parentNode as HTMLSelectElement).name in validator.submitted) {
validator.element(element.parentNode as ValidatableElement);
}
},
highlight: function (this: Validator, element, errorClass, validClass) {
if (element.type === "radio") {
this.findByName(element.name).forEach(x => { x.classList.add(errorClass); x.classList.remove(validClass); });
} else {
if (errorClass != null && errorClass.length)
element.classList.add(errorClass);
if (validClass != null && validClass.length)
element.classList.remove(validClass);
var hl = Validator.getHighlightTarget(element);
if (hl && hl.classList) {
if (errorClass != null && errorClass.length)
hl.classList.add(errorClass);
if (validClass != null && validClass.length)
hl.classList.remove(validClass);
}
}
},
unhighlight: function (this: Validator, element, errorClass, validClass) {
if (element.type === "radio") {
this.findByName(element.name).forEach(x => { x.classList.remove(errorClass); x.classList.add(validClass); });
} else {
if (errorClass != null && errorClass.length)
element.classList.remove(errorClass);
if (validClass != null && validClass.length)
element.classList.add(validClass);
var hl = Validator.getHighlightTarget(element);
if (hl && hl.classList) {
if (errorClass != null && errorClass.length)
hl.classList.remove(errorClass);
if (validClass != null && validClass.length)
hl.classList.add(validClass);
}
}
}
}
static readonly messages: Record<string, string | Function> = {
required: "Validation.Required",
remote: "Please fix this field.",
email: "Validation.Email",
dateQ: "Validation.DateInvalid",
decimalQ: "Validation.Decimal",
dateISO: "Please enter a valid date (ISO).",
integerQ: "Validation.Integer",
number: "Please enter a valid number.",
digits: "Validation.Digits",
equalTo: "Please enter the same value again.",
maxlength: "Validation.MaxLength",
minlength: "Validation.MinLength",
rangelength: "Please enter a value between {0} and {1} characters long.",
range: "Validation.Range",
max: "Please enter a value less than or equal to {0}.",
min: "Please enter a value greater than or equal to {0}.",
step: "Please enter a multiple of {0}.",
url: "Validation.Url",
xss: "Validation.Xss"
}
static readonly methods: Record<string, ValidationProvider> = {
required: function (value, element) {
if (element instanceof HTMLSelectElement) {
// Could be an array for select-multiple or a string, both are fine this way
var val = Validator.elementValue(element);
return val && (val as any).length > 0;
}
if (Validator.isCheckOrRadio(element)) {
return Validator.getLength(value, element) > 0;
}
return value != null && (typeof value === "number" || (value as any).length > 0);
},
customValidate: function (value: ValidationValue, element: ValidatableElement) {
let result = Validator.optional(element);
if (!element || !!result)
return result;
let rules = customValidateRules.get(element);
if (!rules)
return true;
for (let k in rules) {
let handlers = rules[k];
for (let handler of handlers) {
if (typeof handler === "function") {
let message = handler(element);
if (message != null) {
return message;
}
}
}
}
return true;
},
dateQ: function (value: string, element: any) {
var o = Validator.optional(element);
if (o)
return o;
var d = parseDate(value);
if (!d || isNaN(d.valueOf()))
return false;
var z = new Date(d);
z.setHours(0, 0, 0, 0);
return z.getTime() === d.getTime();
},
dateTimeQ: function (value: string, element: any) {
var o = Validator.optional(element);
if (o)
return o;
var d = parseDate(value);
if (!d || isNaN(d.valueOf()))
return false;
return true;
},
/*
hourAndMin: function (value: string, element: any) {
return Validator.optional(element) || !isNaN(parseHourAndMin(value));
}
dayHourAndMin: function (value: string, element: any) {
return Validator.optional(element) || !isNaN(parseDayHourAndMin(value));
});
*/
decimalQ: function (value: string, element: any) {
return Validator.optional(element) || !isNaN(parseDecimal(value));
},
integerQ: function (value: string, element: any) {
return Validator.optional(element) || !isNaN(parseInteger(value));
},
/**
* Validates whether the input value is an email in accordance to RFC822 specification, with a top level domain.
*/
email: (value) => {
if (!value || typeof value !== "string") {
return true;
}
if (!Config.emailAllowOnlyAscii) {
return new RegExp("^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|" +
"[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|" +
"[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|" +
"((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|" +
"\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|" +
"[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|" +
"[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])" +
"([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)" +
"+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|" +
"[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$", "i")
.test(value);
}
// RFC822 email address with .TLD validation
// (c) Richard Willis, Chris Ferdinandi, MIT Licensed
// https://gist.github.com/badsyntax/719800
// https://gist.github.com/cferdinandi/d04aad4ce064b8da3edf21e26f8944c4
let r = /^([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22))*\x40([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d))*(\.\w{2,})+$/;
return r.test(value);
},
minlength: function (value, element, param: number) {
var length = Array.isArray(value) ? value.length : Validator.getLength(value, element);
return Validator.optional(element) || length >= param;
},
maxlength: function (value, element, param: number) {
var length = Array.isArray(value) ? value.length : Validator.getLength(value, element);
return Validator.optional(element) || length <= param;
},
rangelength: function (value, element, param: number[]) {
var length = Array.isArray(value) ? value.length : Validator.getLength(value, element);
return Validator.optional(element) || (length >= param[0] && length <= param[1]);
},
min: function (value, element, param) {
return Validator.optional(element) || value >= param;
},
max: function (value, element, param) {
return Validator.optional(element) || value <= param;
},
range: function (value, element, param) {
return Validator.optional(element) || (value >= param[0] && value <= param[1]);
},
url: function (value, element) {
return Validator.optional(element) || /^(?:(?:(?:https?|ftp):)?\/\/)(?:(?:[^\]\[?\/<~#`!@$^&*()+=}|:";',>{ ]|%[0-9A-Fa-f]{2})+(?::(?:[^\]\[?\/<~#`!@$^&*()+=}|:";',>{ ]|%[0-9A-Fa-f]{2})*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u00a1-\uffff][a-z0-9\u00a1-\uffff_-]{0,62})?[a-z0-9\u00a1-\uffff]\.)+(?:[a-z\u00a1-\uffff]{2,}\.?))(?::\d{2,5})?(?:[/?#]\S*)?$/i.test(value?.toString());
}
}
readonly settings: ValidatorOptions;
public lastActive: ValidatableElement;
private cancelSubmit: boolean;
private currentElements: ValidatableElement[];
private currentForm: HTMLFormElement;
private errorMap: ValidationErrorMap;
private errorList: ValidationErrorList;
private formSubmitted: boolean;
private submitted: Record<string, boolean>;
private submitButton: HTMLInputElement | HTMLButtonElement;
private pendingRequest: number;
private invalid: ValidationErrorMap;
private pending: Record<string, (false | AbortController)>;
private successList: ValidatableElement[];
private toHide: HTMLElement[];
private toShow: HTMLElement[];
constructor(form: HTMLFormElement, options: ValidatorOptions) {
if (validatorMap.get(form))
throw "Form already has a Validator instance!";
validatorMap.set(form, this);
form.setAttribute("novalidate", "novalidate");
this.settings = Object.assign(true, {}, Validator.defaults, options);
this.currentForm = form;
if (this.settings.onsubmit) {
var selector = "[type=submit],button:not([type])";
Fluent.on(this.currentForm, "click.validator", selector, (event: Event) => {
// jquery and dom returns different results for currentTarget
var button = ((event.currentTarget as HTMLElement)?.matches?.(selector) ? event.currentTarget : (event.target as HTMLElement).closest?.(selector) ?? event.target) as HTMLButtonElement;;
// Track the used submit button to properly handle scripted
// submits later.
this.submitButton = button;
// Allow suppressing validation by adding a cancel class to the submit button
if (button.classList?.contains("cancel")) {
this.cancelSubmit = true;
}
// Allow suppressing validation by adding the html5 formnovalidate attribute to the submit button
if (button.getAttribute("formnovalidate") != null) {
this.cancelSubmit = true;
}
});
// Validate the form on submit
Fluent.on(this.currentForm, "submit.validator", (event: Event) => {
if (this.settings.debug) {
// Prevent form submit to be able to see console output
event.preventDefault();
}
const stopSubmit = () => {
event.preventDefault();
event.stopPropagation();
return false;
}
const handle = () => {
var hidden, result;
// Insert a hidden input as a replacement for the missing submit button
// The hidden input is inserted in two cases:
// - A user defined a `submitHandler`
// - There was a pending request due to `remote` method and `stopRequest()`
// was called to submit the form in case it's valid
if (this.submitButton && (this.settings.submitHandler || this.formSubmitted)) {
hidden = Fluent("input").attr("type", "hidden")
.attr("name", this.submitButton.name)
.val(Fluent(this.submitButton).val())
.appendTo(this.currentForm);
}
if (this.settings.submitHandler && !this.settings.debug) {
result = this.settings.submitHandler(this.currentForm, event, this);
if (hidden) {
// And clean up afterwards; thanks to no-block-scope, hidden can be referenced
hidden.remove();
}
if (result !== undefined) {
if (result === false)
return stopSubmit();
return result;
}
return stopSubmit();
}
return true;
}
// Prevent submit for invalid forms or custom submit handlers
if (this.cancelSubmit) {
this.cancelSubmit = false;
return handle();
}
if (this.form()) {
if (this.pendingRequest) {
this.formSubmitted = true;
return stopSubmit();
}
return handle();
} else {
this.focusInvalid();
return stopSubmit();
}
});
}
this.init();
}
static getInstance(element: HTMLFormElement | Node | ArrayLike<HTMLElement>) {
element = isArrayLike(element) ? element[0] : element;
if (!element)
return null;
if (element instanceof HTMLFormElement)
return validatorMap.get(element);
else if ((element as any).form instanceof HTMLFormElement)
return validatorMap.get((element as any).form);
let form = (element as any).closest?.("form");
if (form instanceof HTMLFormElement)
return validatorMap.get(form);
return null;
}
private init() {
this.submitted = {};
this.pendingRequest = 0;
this.pending = {};
this.invalid = {};
this.reset();
["focusin.validator", "focusout.validator", "keyup.validator"].forEach((type) => {
Fluent.on(this.currentForm, type, "[type='text'], [type='password'], [type='file'], select, textarea, [type='number'], [type='search'], " +
"[type='tel'], [type='url'], [type='email'], [type='datetime'], [type='date'], [type='month'], " +
"[type='week'], [type='time'], [type='datetime-local'], [type='range'], [type='color'], " +
"[type='radio'], [type='checkbox'], [contenteditable], [type='button']", validatorEventDelegate);
});
// Support: Chrome, oldIE
// "select" is provided as event.target when clicking a option
Fluent.on(this.currentForm, "click.validator", "select, option, [type='radio'], [type='checkbox']", validatorEventDelegate);
if (this.settings.invalidHandler) {
Fluent.on(this.currentForm, "invalid-form.validator", (e) => this.settings.invalidHandler(e, this));
}
}
/**
* Checks if `element` is validatable (`input`, `select`, `textarea`).
* @param element The element to check.
* @returns `true` if validatable, otherwise `false`.
*/
static isValidatableElement(element: EventTarget): element is ValidatableElement {
return element instanceof HTMLInputElement || element instanceof HTMLSelectElement || element instanceof HTMLTextAreaElement;
}
static isCheckOrRadio(element: Node): element is HTMLInputElement {
return element instanceof HTMLInputElement && (/radio|checkbox/i).test(element.type);
}
static getLength(value: ValidationValue, element: HTMLElement): number {
if (element instanceof HTMLSelectElement)
return element.querySelectorAll("option:selected").length;
if (element instanceof HTMLInputElement && Validator.isCheckOrRadio(element)) {
if (!element.name)
return element.checked ? 1 : 0;
return Array.from(element.form?.querySelectorAll(`[name=${element.name}]`)).filter(x => (x as any).checked).length || 0;
}
return typeof value === "number" ? ("" + value).length : (value as any).length;
}
static isContentEditable(element: HTMLElement) {
let val = element.getAttribute("contenteditable");
return val != null && val !== "false"
}
static elementValue(element: HTMLElement) {
if (element instanceof Element && Validator.isContentEditable(element)) {
return element.textContent;
}
if (element instanceof HTMLInputElement) {
if (element.type === "radio" || element.type === "checkbox") {
if (element.name && element.form) {
var values = Array.from(element.form.querySelectorAll<HTMLInputElement>(`input[name=${CSS.escape(element.name)}]`))
.map(el => el.checked ? null : el.value);
if (values.length > 1)
return values.filter(x => x != null);
return values[0];
}
return element.checked ? element.value : null;
}
if (element.type === "number") {
if (typeof element.validity !== "undefined")
return element.validity.badInput ? NaN : element.valueAsNumber;
else
return element.valueAsNumber;
}
var val;
if (element.type === "file") {
val = element.value ?? "";
// Modern browser (chrome & safari)
if (val.substring(0, 12) === "C:\\fakepath\\") {
return val.substring(12);
}
// Legacy browsers
// Unix-based path
var idx = val.lastIndexOf("/");
if (idx >= 0) {
return val.substr(idx + 1);
}
// Windows-based path
idx = val.lastIndexOf("\\");
if (idx >= 0) {
return val.substring(idx + 1);
}
// Just the file name
return val;
}
val = element.value;
} else if (element instanceof HTMLTextAreaElement) {
val = element.value;
} else if (element instanceof HTMLSelectElement) {
val = element.value;
}
if (typeof val === "string")
return val.replace(/\r/g, "");
return val;
}
static valid(element: HTMLFormElement | ValidatableElement | ArrayLike<ValidatableElement>): boolean {
element = element instanceof HTMLFormElement ? element : isArrayLike(element) ? element[0] : element;
if (!element)
return false;
let validator = Validator.getInstance(element);
if (!validator)
return false;
if (element instanceof HTMLFormElement)
return validator.form();
return validator.element(element);
}
static rules(element: ValidatableElement, command?: "add" | "remove", argument?: any) {
let isContentEditable = Validator.isContentEditable(element);
//settings, staticRules, existingRules, data, param, filtered;
// If nothing is selected, return empty object; can't chain anyway
if (element == null) {
return;
}
if (!element.form && isContentEditable) {
(element as any).form = element.closest("form");
element.name = element.getAttribute("name");
}
if (element.form == null) {
return;
}
if (command) {
var validator = Validator.getInstance(element.form);
if (validator) {
let settings = validator.settings;
let staticRules = settings.rules;
let existingRules = Validator.staticRules(element);
switch (command) {
case "add":
Object.assign(existingRules, argument);
// Remove messages from rules, but allow them to be set separately
delete existingRules.messages;
staticRules[element.name] = existingRules;
if (argument.messages) {
settings.messages[element.name] = Object.assign(settings.messages[element.name], argument.messages);
}
break;
case "remove":
if (!argument) {
delete staticRules[element.name];
return existingRules;
}
var filtered: Record<string, any> = {};
argument.split(/\s/).forEach((method: string) => {
filtered[method] = existingRules[method];
delete existingRules[method];
});
return filtered;
}
}
}
var data = Validator.normalizeRules(
Object.assign({},
Validator.classRules(element),
Validator.attributeRules(element),
Validator.dataRules(element),
Validator.staticRules(element)
), element);
// Make sure required is at front
if (data.required) {
var param = data.required;
delete data.required;
data = Object.assign({ required: param }, data);
}
// Make sure remote is at back
if (data.remote) {
param = data.remote;
delete data.remote;
data = Object.assign(data, { remote: param });
}
return data;
}
form() {
this.checkForm();
Object.assign(this.submitted, this.errorMap);
this.invalid = Object.assign({}, this.errorMap);
if (!this.valid()) {
Fluent.trigger(this.currentForm, "invalid-form", { validator: this });
}
this.showErrors();
return this.valid();
}
checkForm() {
this.prepareForm();
for (var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++) {
this.check(elements[i]);
}
return this.valid();
}
element(element: ValidatableElement) {
var checkElement = this.validationTargetFor(element),
result = true,
rs;
if (checkElement === void 0) {
delete this.invalid[element.name];
} else {
this.prepareElement(checkElement);
this.currentElements = [checkElement];
rs = this.check(checkElement) !== false;
result = result && rs;
if (rs) {
this.invalid[checkElement.name] = false;
} else {
this.invalid[checkElement.name] = true;
}
this.showErrors();
// Add aria-invalid status for screen readers
if (rs)
element.setAttribute("aria-invalid", "true");
else
element.removeAttribute("aria-invalid");
}
return result;
}
showErrors(errors?: ValidationErrorMap) {
if (errors) {
// Add items to error list and map
Object.assign(this.errorMap, errors);
this.errorList = Object.keys(this.errorMap).map(name => ({
message: this.errorMap[name] as string,
element: this.findByName(name)[0]
}));
// Remove items from success list
this.successList = this.successList.filter(function (element) {
return !(element.name in errors);
});
}
if (this.settings.showErrors) {
this.settings.showErrors(this.errorMap, this.errorList, this);
} else {
this.defaultShowErrors();
}
}
resetForm() {
this.invalid = {};
this.submitted = {};
this.prepareForm();
this.hideErrors();
var elements = this.elements();
elements.forEach(x => {
delete (x as any).previousValue;
x.removeAttribute("aria-invalid");
});
this.resetElements(elements);
}
resetElements(elements: ValidatableElement[]) {
var i;
if (this.settings.unhighlight) {
for (i = 0; elements[i]; i++) {
this.settings.unhighlight(elements[i], this.settings.errorClass, "", this);
this.findByName(elements[i].name).forEach(x => x.classList.remove(this.settings.validClass));
}
} else {
elements.forEach(x => {
x.classList.remove(this.settings.errorClass);
x.classList.remove(this.settings.validClass);
});
}
}
numberOfInvalids() {
return Validator.objectLength(this.invalid);
}
private static objectLength(obj: Record<string, any>) {
/* jshint unused: false */
var count = 0,
i;
for (i in obj) {
// This check allows counting elements with empty error
// message as invalid elements
if (obj[i] !== undefined && obj[i] !== null && obj[i] !== false) {
count++;
}
}
return count;
}
hideErrors() {
this.hideThese(this.toHide);
}
hideThese(errors: HTMLElement[]) {
errors.forEach(x => {
x.textContent = "";
(x as HTMLElement).style.display = "none";
});
}
valid() {
return this.size() === 0;
}
size() {
return this.errorList.length;
}
focusInvalid() {
if (this.settings.abortHandler)
this.settings.abortHandler(this);
if (this.settings.focusInvalid) {
try {
var lastActive = this.findLastActive() || (this.errorList.length && this.errorList[0].element);
if (lastActive && Fluent.isVisibleLike(lastActive)) {