/
index.ts
1264 lines (1088 loc) · 42.3 KB
/
index.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
/**
* A simple IDictionary<string, string>
*/
export interface StringKeyValuePair {
[key: string]: string
}
/**
* A duplex key-value pair for an element, by GUID or its DOM object reference.
*/
interface ElementUID {
node: Element,
uid: string;
}
/**
* A simple logging interface that mirrors the Console object.
*/
export interface Logger {
log(message: string, ...args: any[]): void;
warn(message: string, ...args: any[]): void;
}
const nullLogger = new (class implements Logger {
log(_: string, ..._args: any[]): void { }
warn = globalThis.console.warn;
})();
/**
* An `HTMLElement` that can be validated (`input`, `select`, `textarea`).
*/
export type ValidatableElement = HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement;
/**
* Checks if `element` is validatable (`input`, `select`, `textarea`).
* @param element The element to check.
* @returns `true` if validatable, otherwise `false`.
*/
export const isValidatable = (element: Node): element is ValidatableElement =>
element instanceof HTMLInputElement
|| element instanceof HTMLSelectElement
|| element instanceof HTMLTextAreaElement;
const validatableElementTypes = ['input', 'select', 'textarea'];
/**
* Generates a selector to match validatable elements (`input`, `select`, `textarea`).
* @param selector An optional selector to apply to the valid input types, e.g. `[data-val="true"]`.
* @returns The validatable elements.
*/
const validatableSelector = (selector?: string) =>
validatableElementTypes.map(t => `${t}${selector || ''}`).join(',');
/**
* Parameters passed into validation providers from the element attributes.
* error property is read from data-val-[Provider Name] attribute.
* params property is populated from data-val-[Provider Name]-[Parameter Name] attributes.
*/
export interface ValidationDirectiveBindings {
error: string,
params: StringKeyValuePair
}
/**
* A key-value pair describing what validations to enforce to an input element, with respective parameters.
*/
export type ValidationDirective = {
[key: string]: ValidationDirectiveBindings
};
/**
* 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: string, element: ValidatableElement, params: StringKeyValuePair) => boolean | string | Promise<boolean | string>;
/**
* Callback to receive the result of validating a form.
*/
export type ValidatedCallback = (success: boolean) => void;
/**
* A callback method signature that kickstarts a new validation task for an input element, as a Boolean Promise.
*/
type Validator = () => Promise<boolean>;
/**
* Resolves and returns the element referred by original element using ASP.NET selector logic.
* @param element - The input to validate
* @param selector - Used to find the field. Ex. *.Password where * replaces whatever prefixes asp.net might add.
*/
function getRelativeFormElement(element: ValidatableElement, selector: string): ValidatableElement {
// example elementName: Form.PasswordConfirm, Form.Email
// example selector (dafuq): *.Password, *.__RequestVerificationToken
// example result element name: Form.Password, __RequestVerificationToken
let elementName = element.name;
let selectedName = selector.substring(2); // Password, __RequestVerificationToken
let objectName = '';
let dotLocation = elementName.lastIndexOf('.');
if (dotLocation > -1) {
// Form
objectName = elementName.substring(0, dotLocation);
// Form.Password
let relativeElementName = objectName + '.' + selectedName;
let relativeElement = document.getElementsByName(relativeElementName)[0];
if (isValidatable(relativeElement)) {
return relativeElement;
}
}
// __RequestVerificationToken
return element.form.querySelector(validatableSelector(`[name=${selectedName}]`));
}
/**
* Contains default implementations for ASP.NET Core MVC validation attributes.
*/
export class MvcValidationProviders {
/**
* Validates whether the input has a value.
*/
required: ValidationProvider = (value, element, params) => {
// Handle single and multiple checkboxes/radio buttons.
const elementType = element.type.toLowerCase();
if (elementType === "checkbox" || elementType === "radio") {
const allElementsOfThisName = Array.from(element.form.querySelectorAll(`input[name='${element.name}'][type='${elementType}']`));
for (let element of allElementsOfThisName) {
if (element instanceof HTMLInputElement && element.checked === true) {
return true;
}
}
// Checkboxes do not submit a value when unchecked. To work around this, platforms such as ASP.NET render a
// hidden input with the same name as the checkbox so that a value ("false") is still submitted even when
// the checkbox is not checked. We check this special case here.
if (elementType === "checkbox") {
const checkboxHiddenInput = element.form.querySelector(`input[name='${element.name}'][type='hidden']`);
if (checkboxHiddenInput instanceof HTMLInputElement && checkboxHiddenInput.value === "false") {
return true;
}
}
return false;
}
// Default behavior otherwise.
return Boolean(value);
}
/**
* Validates whether the input value satisfies the length contstraint.
*/
stringLength: ValidationProvider = (value, element, params) => {
if (!value) {
return true;
}
if (params.min) {
let min = parseInt(params.min);
if (value.length < min) {
return false;
}
}
if (params.max) {
let max = parseInt(params.max);
if (value.length > max) {
return false;
}
}
return true;
}
/**
* Validates whether the input value is equal to another input value.
*/
compare: ValidationProvider = (value, element, params) => {
if (!params.other) {
return true;
}
let otherElement = getRelativeFormElement(element, params.other);
if (!otherElement) {
return true;
}
return (otherElement.value === value);
}
/**
* Validates whether the input value is a number within a given range.
*/
range: ValidationProvider = (value, element, params) => {
if (!value) {
return true;
}
let val = parseFloat(value);
if (isNaN(val)) {
return false;
}
if (params.min) {
let min = parseFloat(params.min);
if (val < min) {
return false;
}
}
if (params.max) {
let max = parseFloat(params.max);
if (val > max) {
return false;
}
}
return true;
}
/**
* Validates whether the input value satisfies a regular expression pattern.
*/
regex: ValidationProvider = (value, element, params) => {
if (!value || !params.pattern) {
return true;
}
let r = new RegExp(params.pattern);
return r.test(value);
}
/**
* Validates whether the input value is an email in accordance to RFC822 specification, with a top level domain.
*/
email: ValidationProvider = (value, element, params) => {
if (!value) {
return true;
}
// 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);
}
/**
* Validates whether the input value is a credit card number, with Luhn's Algorithm.
*/
creditcard: ValidationProvider = (value, element, params) => {
if (!value) {
return true;
}
// (c) jquery-validation, MIT Licensed
// https://github.com/jquery-validation/jquery-validation/blob/master/src/additional/creditcard.js
// based on https://en.wikipedia.org/wiki/Luhn_algorithm
// Accept only spaces, digits and dashes
if (/[^0-9 \-]+/.test(value)) {
return false;
}
var nCheck = 0,
nDigit = 0,
bEven = false,
n, cDigit;
value = value.replace(/\D/g, "");
// Basing min and max length on https://developer.ean.com/general_info/Valid_Credit_Card_Types
if (value.length < 13 || value.length > 19) {
return false;
}
for (n = value.length - 1; n >= 0; n--) {
cDigit = value.charAt(n);
nDigit = parseInt(cDigit, 10);
if (bEven) {
if ((nDigit *= 2) > 9) {
nDigit -= 9;
}
}
nCheck += nDigit;
bEven = !bEven;
}
return (nCheck % 10) === 0;
}
/**
* Validates whether the input value is a URL.
*/
url: ValidationProvider = (value, element, params) => {
if (!value) {
return true;
}
let lowerCaseValue = value.toLowerCase();
// Match the logic in `UrlAttribute`
return lowerCaseValue.indexOf('http://') > -1
|| lowerCaseValue.indexOf('https://') > -1
|| lowerCaseValue.indexOf('ftp://') > -1;
}
/**
* Validates whether the input value is a phone number.
*/
phone: ValidationProvider = (value, element, params) => {
if (!value) {
return true;
}
// Allows whitespace or dash as number separator because some people like to do that...
let consecutiveSeparator = /[\+\-\s][\-\s]/g;
if (consecutiveSeparator.test(value)) {
return false;
}
let r = /^\+?[0-9\-\s]+$/;
return r.test(value);
}
/**
* Asynchronously validates the input value to a JSON GET API endpoint.
*/
remote: ValidationProvider = (value, element, params) => {
if (!value) {
return true;
}
// params.additionalfields: *.Email,*.Username
let fieldSelectors: string[] = (params.additionalfields as string).split(',');
let fields: StringKeyValuePair = {};
for (let fieldSelector of fieldSelectors) {
let fieldName = fieldSelector.substr(2);
let fieldElement = getRelativeFormElement(element, fieldSelector);
let hasValue = Boolean(fieldElement && fieldElement.value);
if (!hasValue) {
continue;
}
fields[fieldName] = fieldElement.value;
}
let url: string = params['url'];
let encodedParams: string[] = [];
for (let fieldName in fields) {
let encodedParam = encodeURIComponent(fieldName) + '=' + encodeURIComponent(fields[fieldName]);
encodedParams.push(encodedParam);
}
let payload = encodedParams.join('&');
return new Promise((ok, reject) => {
let request = new XMLHttpRequest();
if (params.type === 'Post') {
let postData = new FormData();
for (let fieldName in fields) {
postData.append(fieldName, fields[fieldName]);
}
request.open('post', url);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
request.send(payload);
} else {
request.open('get', url + '?' + payload);
request.send();
}
request.onload = e => {
if (request.status >= 200 && request.status < 300) {
let data = JSON.parse(request.responseText);
ok(data);
} else {
reject({
status: request.status,
statusText: request.statusText,
data: request.responseText
});
}
};
request.onerror = e => {
reject({
status: request.status,
statusText: request.statusText,
data: request.responseText
});
};
});
}
}
/**
* Responsible for managing the DOM elements and running the validation providers.
*/
export class ValidationService {
/**
* A key-value collection of loaded validation plugins.
*/
private providers: { [name: string]: ValidationProvider } = {};
/**
* A key-value collection of <span> elements for displaying validation messages for an input (by DOM ID).
*/
private messageFor: { [id: string]: Element[] } = {};
/**
* A list of managed elements, each having a randomly assigned unique identifier (UID).
*/
private elementUIDs: ElementUID[] = [];
/**
* A key-value collection of UID to Element for quick lookup.
*/
private elementByUID: { [uid: string]: Element } = {};
/**
* A key-value collection of input UIDs for a <form> UID.
*/
private formInputs: { [formUID: string]: string[] } = {};
/**
* A key-value map for input UID to its validator factory.
*/
private validators: { [inputUID: string]: Validator } = {};
/**
* A key-value map for element UID to its trigger element (submit event for <form>, input event for <textarea> and <input>).
*/
private elementEvents: { [id: string]: (e?: SubmitEvent, callback?: ValidatedCallback) => void } = {};
/**
* A key-value map of input UID to its validation error message.
*/
private summary: StringKeyValuePair = {};
/**
* A serialized representation of the validation error message summary rendered to the user.
*/
private renderedSummaryJSON: string;
/**
* In milliseconds, the rate of fire of the input validation.
*/
debounce = 300;
/**
* Allow hidden fields validation
*/
allowHiddenFields = false;
private logger: Logger;
observer?: MutationObserver;
constructor(logger?: Logger) {
this.logger = logger || nullLogger;
}
/**
* Registers a new validation plugin of the given name, if not registered yet.
* Registered plugin validates inputs with data-val-[name] attribute, used as error message.
* @param name
* @param callback
*/
addProvider(name: string, callback: ValidationProvider) {
if (this.providers[name]) {
// First-Come-First-Serve validation plugin design.
// Allows developers to override the default MVC Providers by adding custom providers BEFORE bootstrap() is called!
return;
}
this.logger.log("Registered provider: %s", name);
this.providers[name] = callback;
}
/**
* Registers the default providers for enabling ASP.NET Core MVC client-side validation.
*/
private addMvcProviders() {
let mvc = new MvcValidationProviders();
// [Required]
this.addProvider('required', mvc.required);
// [StringLength], [MinLength], [MaxLength]
this.addProvider('length', mvc.stringLength);
this.addProvider('maxlength', mvc.stringLength);
this.addProvider('minlength', mvc.stringLength);
// [Compare]
this.addProvider('equalto', mvc.compare);
// [Range]
this.addProvider('range', mvc.range);
// [RegularExpression]
this.addProvider('regex', mvc.regex);
// [CreditCard]
this.addProvider('creditcard', mvc.creditcard);
// [EmailAddress]
this.addProvider('email', mvc.email);
// [Url]
this.addProvider('url', mvc.url);
// [Phone]
this.addProvider('phone', mvc.phone);
// [Remote]
this.addProvider('remote', mvc.remote);
}
/**
* Scans document for all validation message <span> generated by ASP.NET Core MVC, then tracks them.
*/
private scanMessages(root: ParentNode) {
/* If a validation span explicitly declares a form, we group the span with that form. */
let validationMessageElements = Array.from(root.querySelectorAll<HTMLElement>('span[form]'));
for (let span of validationMessageElements) {
let form = document.getElementById(span.getAttribute('form'));
if (form) {
this.pushValidationMessageSpan(form, span);
}
}
// Otherwise if a validation message span is inside a form, we group the span with the form it's inside.
let forms = Array.from(root.querySelectorAll<HTMLFormElement>('form'));
if (root instanceof HTMLFormElement) {
// querySelectorAll does not include the root element itself.
// we could use 'matches', but that's newer than querySelectorAll so we'll keep it simple and compatible.
forms.push(root);
}
for (let form of forms) {
let validationMessageElements = Array.from(form.querySelectorAll<HTMLElement>('[data-valmsg-for]'));
for (let span of validationMessageElements) {
this.pushValidationMessageSpan(form, span);
}
}
}
private pushValidationMessageSpan(form: HTMLElement, span: HTMLElement) {
let formId = this.getElementUID(form);
let name = `${formId}:${span.getAttribute('data-valmsg-for')}`;
let spans = this.messageFor[name] || (this.messageFor[name] = []);
if (spans.indexOf(span) < 0) {
spans.push(span);
}
else {
this.logger.log("Validation element for '%s' is already tracked", name, span);
}
}
/**
* Given attribute map for an HTML input, returns the validation directives to be executed.
* @param attributes
*/
parseDirectives(attributes: NamedNodeMap) {
let directives: ValidationDirective = {};
let validationAtributes: StringKeyValuePair = {};
let cut = 'data-val-'.length;
for (let i = 0; i < attributes.length; i++) {
let a = attributes[i];
if (a.name.indexOf('data-val-') === 0) {
let key = a.name.substr(cut);
validationAtributes[key] = a.value;
}
}
for (let key in validationAtributes) {
if (key.indexOf('-') === -1) {
let parameters = Object.keys(validationAtributes).filter(Q => {
return (Q !== key) && (Q.indexOf(key) === 0);
});
let directive: ValidationDirectiveBindings = {
error: validationAtributes[key],
params: {}
};
let pcut = (key + '-').length;
for (let i = 0; i < parameters.length; i++) {
let pvalue = validationAtributes[parameters[i]];
let pkey = parameters[i].substr(pcut);
directive.params[pkey] = pvalue;
}
directives[key] = directive;
}
}
return directives;
}
/**
* Returns an RFC4122 version 4 compliant GUID.
*/
private guid4() {
// (c) broofa, MIT Licensed
// https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript/2117523#2117523
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
/**
* Gets a UID for an DOM element.
* @param node
*/
private getElementUID(node: Element) {
let x = this.elementUIDs.filter(e => {
return e.node === node;
})[0];
if (x) {
return x.uid;
}
let uid = this.guid4();
this.elementUIDs.push({
node: node,
uid: uid
});
this.elementByUID[uid] = node;
return uid;
}
/**
* Returns a Promise that returns validation result for each and every inputs within the form.
* @param formUID
*/
private getFormValidationTask(formUID: string) {
let formInputUIDs = this.formInputs[formUID];
if (!formInputUIDs || formInputUIDs.length === 0) {
return Promise.resolve(true);
}
let formValidators: Validator[] = [];
for (let i = 0; i < formInputUIDs.length; i++) {
let inputUID = formInputUIDs[i];
formValidators.push(this.validators[inputUID]);
}
let tasks = formValidators.map(factory => factory());
return Promise.all(tasks).then(result => result.every(e => e));
}
// Retrieves the validation span for the input.
private getMessageFor(input: ValidatableElement) {
if (!input.form) {
return [];
}
let formId = this.getElementUID(input.form);
let name = `${formId}:${input.name}`;
return this.messageFor[name];
}
/**
* Fires off validation for elements within the provided form and then calls the callback
* @param form
* @param callback
*/
validateForm = (form: HTMLFormElement, callback?: ValidatedCallback) => {
let formUID = this.getElementUID(form);
let formValidationEvent = this.elementEvents[formUID];
if (formValidationEvent) {
formValidationEvent(undefined, callback);
}
}
/**
* Called before validating form submit events.
* Default calls `preventDefault()` and `stopImmediatePropagation()`.
* @param submitEvent The `SubmitEvent`.
*/
preValidate = (submitEvent: SubmitEvent) => {
submitEvent.preventDefault();
submitEvent.stopImmediatePropagation();
}
/**
* Handler for validated form submit events.
* Default calls `submitValidForm(form, submitEvent)` on success
* and `focusFirstInvalid(form)` on failure.
* @param form The form that has been validated.
* @param success The validation result.
* @param submitEvent The `SubmitEvent`.
*/
handleValidated = (form: HTMLFormElement, success: boolean, submitEvent: SubmitEvent) => {
if (success) {
this.submitValidForm(form, submitEvent);
}
else {
this.focusFirstInvalid(form);
}
}
/**
* Dispatches a new `SubmitEvent` on the provided form,
* then calls `form.submit()` unless `submitEvent` is cancelable
* and `preventDefault()` was called by a handler that received the new event.
*
* This is equivalent to `form.requestSubmit()`, but more flexible.
* @param form The validated form to submit
* @param submitEvent The `SubmitEvent`.
*/
submitValidForm = (form: HTMLFormElement, submitEvent: SubmitEvent) => {
const newEvent = new SubmitEvent('submit', submitEvent);
if (form.dispatchEvent(newEvent)) {
// Because the submitter is not propagated when calling
// form.submit(), we recreate it here.
const submitter = submitEvent.submitter;
if (submitter) {
const name = submitter.getAttribute('name');
// If name is null, a submit button is not submitted.
if (name) {
const submitterInput = document.createElement('input');
submitterInput.type = 'hidden';
submitterInput.name = name;
submitterInput.value = submitter.getAttribute('value');
form.appendChild(submitterInput)
}
}
form.submit();
}
}
/**
* Focuses the first invalid element within the provided form
* @param form
*/
focusFirstInvalid = (form: HTMLFormElement) => {
let formUID = this.getElementUID(form);
let formInputUIDs = this.formInputs[formUID];
let invalidFormInputUIDs = formInputUIDs.filter(uid => this.summary[uid]);
if (invalidFormInputUIDs.length > 0) {
var firstInvalid = this.elementByUID[invalidFormInputUIDs[0]] as HTMLElement;
if (firstInvalid) {
firstInvalid.focus();
}
}
}
/**
* Returns true if the provided form is valid, and then calls the callback. The form will be validated before checking, unless prevalidate is set to false
* @param form
* @param prevalidate
* @param callback
* @returns
*/
isValid = (form: HTMLFormElement, prevalidate: boolean = true, callback?: ValidatedCallback) => {
if (prevalidate) {
this.validateForm(form, callback);
}
let formUID = this.getElementUID(form);
let formInputUIDs = this.formInputs[formUID];
let invalidFormInputUIDs = formInputUIDs.filter(uid => this.summary[uid]);
return invalidFormInputUIDs.length == 0;
}
/**
* Returns true if the provided field is valid, and then calls the callback. The form will be validated before checking, unless prevalidate is set to false
* @param field
* @param prevalidate
* @param callback
* @returns
*/
isFieldValid = (field: HTMLElement, prevalidate: boolean = true, callback?: ValidatedCallback) => {
if (prevalidate) {
let form = field.closest("form");
if (form != null) {
this.validateForm(form, callback);
}
}
let fieldUID = this.getElementUID(field);
return this.summary[fieldUID] != null;
}
/**
* Returns true if the event triggering the form submission indicates we should validate the form.
* @param e
*/
private shouldValidate(e?: Event) {
// Skip client-side validation if the form has been submitted via a button that has the "formnovalidate" attribute.
return !(e && e['submitter'] && e['submitter']['formNoValidate']);
}
/**
* Tracks a <form> element as parent of an input UID. When the form is submitted, attempts to validate the said input asynchronously.
* @param form
* @param inputUID
*/
private trackFormInput(form: HTMLFormElement, inputUID: string) {
let formUID = this.getElementUID(form);
if (!this.formInputs[formUID]) {
this.formInputs[formUID] = [];
}
let add = (this.formInputs[formUID].indexOf(inputUID) === -1);
if (add) {
this.formInputs[formUID].push(inputUID);
}
else {
this.logger.log("Form input for UID '%s' is already tracked", inputUID);
}
if (this.elementEvents[formUID]) {
return;
}
let validating = false;
let cb = (e?: SubmitEvent, callback?: ValidatedCallback) => {
// Prevent recursion
if (validating) {
return;
}
if (!this.shouldValidate(e)) {
return;
}
let validate = this.getFormValidationTask(formUID);
if (!validate) {
return;
}
//`preValidate` typically prevents submit before validation
if (e) {
this.preValidate(e);
}
validating = true;
this.logger.log('Validating', form);
validate.then(success => {
this.logger.log('Validated (success = %s)', success, form);
if (callback) {
callback(success);
return;
}
const validationEvent = new CustomEvent('validation',
{
detail: { valid: success }
});
form.dispatchEvent(validationEvent);
this.handleValidated(form, success, e);
}).catch(error => {
this.logger.log('Validation error', error);
}).finally(() => {
validating = false;
});
};
form.addEventListener('submit', cb);
form.addEventListener('reset', e => {
let uids = this.formInputs[formUID];
for (let uid of uids) {
let input = this.elementByUID[uid] as ValidatableElement;
if (input.classList.contains(this.ValidationInputCssClassName)) {
input.classList.remove(this.ValidationInputCssClassName);
}
if (input.classList.contains(this.ValidationInputValidCssClassName)) {
input.classList.remove(this.ValidationInputValidCssClassName);
}
let spans = this.getMessageFor(input);
if (spans) {
for (let i = 0; i < spans.length; i++) {
spans[i].innerHTML = '';
}
}
delete this.summary[uid];
}
this.renderSummary();
});
this.elementEvents[formUID] = cb;
}
/**
* Adds an input element to be managed and validated by the service.
* Triggers a debounced live validation when input value changes.
* @param input
*/
addInput(input: ValidatableElement) {
let uid = this.getElementUID(input);
let directives = this.parseDirectives(input.attributes);
this.validators[uid] = this.createValidator(input, directives);
if (input.form) {
this.trackFormInput(input.form, uid);
}
if (this.elementEvents[uid]) {
return;
}
let delay;
let cb = e => {
let validate = this.validators[uid];
clearTimeout(delay);
delay = setTimeout(validate, this.debounce);
};
let isDropdown = input.tagName.toLowerCase() === 'select';
let validateEvent = input.dataset.valEvent;
if (isDropdown) {
input.addEventListener('change', cb);
} else if (validateEvent) {
input.addEventListener(validateEvent, cb);
}
else {
input.addEventListener('input', cb);
}
this.elementEvents[uid] = cb;
}
/**
* Scans the entire document for input elements to be validated.
*/
private scanInputs(root: ParentNode) {
let inputs = Array.from(root.querySelectorAll<ValidatableElement>(validatableSelector('[data-val="true"]')));
// querySelectorAll does not include the root element itself.
// we could use 'matches', but that's newer than querySelectorAll so we'll keep it simple and compatible.
if (isValidatable(root) && root.getAttribute("data-val") === "true") {
inputs.push(root);
}
for (let i = 0; i < inputs.length; i++) {
let input = inputs[i];
this.addInput(input);
}
}
/**
* Returns a <ul> element as a validation errors summary.
*/
createSummaryDOM() {
if (!Object.keys(this.summary).length) {
return null;
}
let ul = document.createElement('ul');
for (let key in this.summary) {
let li = document.createElement('li');
li.innerHTML = this.summary[key];
ul.appendChild(li);
}
return ul;
}
/**
* Displays validation summary to ASP.NET Core MVC designated elements, when it actually gets updated.
*/
private renderSummary() {
let summaryElements = document.querySelectorAll('[data-valmsg-summary="true"]');
if (!summaryElements.length) {
return;
}
// Using JSON.stringify for quick and painless deep compare of simple KVP. You need to sort the keys first, tho...
let shadow = JSON.stringify(this.summary, Object.keys(this.summary).sort());
if (shadow === this.renderedSummaryJSON) {
return;
}
// Prevents wasteful re-rendering of summary list element with identical items!
this.renderedSummaryJSON = shadow;
let ul = this.createSummaryDOM();
for (let i = 0; i < summaryElements.length; i++) {
let e = summaryElements[i];
e.innerHTML = '';
if (ul) {
this.swapClasses(e,
this.ValidationSummaryCssClassName,
this.ValidationSummaryValidCssClassName)
e.appendChild(ul.cloneNode(true));
} else {
this.swapClasses(e,