Skip to content

Commit 4abfdc4

Browse files
authored
Merge pull request #32 from dahlbyk/handleValidated
Extract `handleValidated`
2 parents da04d3c + c3a6e18 commit 4abfdc4

File tree

7 files changed

+95
-61
lines changed

7 files changed

+95
-61
lines changed

dist/aspnet-validation.js

Lines changed: 29 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -458,9 +458,31 @@ var ValidationService = /** @class */ (function () {
458458
var formUID = _this.getElementUID(form);
459459
var formValidationEvent = _this.elementEvents[formUID];
460460
if (formValidationEvent) {
461-
formValidationEvent(null, callback);
461+
formValidationEvent(undefined, callback);
462462
}
463463
};
464+
/**
465+
* Handler for validated form submit events.
466+
* Default calls `submitValidForm(form)` on success
467+
* and `focusFirstInvalid(form)` on failure.
468+
* @param form The form that has been validated.
469+
* @param success The validation result.
470+
*/
471+
this.handleValidated = function (form, success) {
472+
if (success) {
473+
_this.submitValidForm(form);
474+
}
475+
else {
476+
_this.focusFirstInvalid(form);
477+
}
478+
};
479+
/**
480+
* Calls `requestSubmit()` on the provided form.
481+
* @param form The validated form to submit
482+
*/
483+
this.submitValidForm = function (form) {
484+
form.requestSubmit();
485+
};
464486
/**
465487
* Focuses the first invalid element within the provided form
466488
* @param form
@@ -678,7 +700,7 @@ var ValidationService = /** @class */ (function () {
678700
ValidationService.prototype.getFormValidationTask = function (formUID) {
679701
var formInputUIDs = this.formInputs[formUID];
680702
if (!formInputUIDs || formInputUIDs.length === 0) {
681-
return null;
703+
return Promise.resolve(true);
682704
}
683705
var formValidators = [];
684706
for (var i = 0; i < formInputUIDs.length; i++) {
@@ -694,7 +716,7 @@ var ValidationService = /** @class */ (function () {
694716
*/
695717
ValidationService.prototype.shouldValidate = function (e) {
696718
// Skip client-side validation if the form has been submitted via a button that has the "formnovalidate" attribute.
697-
return !(e !== null && e['submitter'] && e['submitter']['formNoValidate']);
719+
return !(e && e['submitter'] && e['submitter']['formNoValidate']);
698720
};
699721
/**
700722
* Tracks a <form> element as parent of an input UID. When the form is submitted, attempts to validate the said input asynchronously.
@@ -739,30 +761,15 @@ var ValidationService = /** @class */ (function () {
739761
_this.logger.log('Validating', form);
740762
validate.then(function (success) {
741763
_this.logger.log('Validated (success = %s)', success, form);
742-
var isProgrammaticValidate = !e;
743-
if (success) {
744-
if (isProgrammaticValidate) {
745-
callback(true);
746-
return;
747-
}
748-
var validationEvent_1 = new CustomEvent('validation', {
749-
detail: { valid: true }
750-
});
751-
form.dispatchEvent(validationEvent_1);
752-
//Resubmit the form here, after the async validation is completed.
753-
form.requestSubmit();
764+
if (callback) {
765+
callback(success);
754766
return;
755767
}
756768
var validationEvent = new CustomEvent('validation', {
757-
detail: { valid: false }
769+
detail: { valid: success }
758770
});
759771
form.dispatchEvent(validationEvent);
760-
if (isProgrammaticValidate) {
761-
callback(false);
762-
}
763-
else {
764-
_this.focusFirstInvalid(form);
765-
}
772+
_this.handleValidated(form, success);
766773
}).catch(function (error) {
767774
_this.logger.log('Validation error', error);
768775
}).finally(function () {

dist/aspnet-validation.min.js

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

dist/aspnet-validation.min.js.map

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package-lock.json

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "aspnet-client-validation",
3-
"version": "0.8.3",
3+
"version": "0.8.4",
44
"description": "Enables ASP.NET MVC client-side validation, without jQuery!",
55
"main": "dist/aspnet-validation.js",
66
"style": "dist/aspnet-validation.css",

src/index.ts

Lines changed: 41 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,11 @@ export type ValidationDirective = {
4949
*/
5050
export type ValidationProvider = (value: string, element: HTMLInputElement, params: StringKeyValuePair) => boolean | string | Promise<boolean | string>;
5151

52+
/**
53+
* Callback to receive the result of validating a form.
54+
*/
55+
export type ValidatedCallback = (success: boolean) => void;
56+
5257
/**
5358
* A callback method signature that kickstarts a new validation task for an input element, as a Boolean Promise.
5459
*/
@@ -385,7 +390,7 @@ export class ValidationService {
385390
/**
386391
* A key-value map for element UID to its trigger element (submit event for <form>, input event for <textarea> and <input>).
387392
*/
388-
private elementEvents: { [id: string]: (e: Event, callback?: Function) => any } = {};
393+
private elementEvents: { [id: string]: (e?: Event, callback?: ValidatedCallback) => void } = {};
389394

390395
/**
391396
* A key-value map of input UID to its validation error message.
@@ -572,7 +577,7 @@ export class ValidationService {
572577
private getFormValidationTask(formUID: string) {
573578
let formInputUIDs = this.formInputs[formUID];
574579
if (!formInputUIDs || formInputUIDs.length === 0) {
575-
return null;
580+
return Promise.resolve(true);
576581
}
577582

578583
let formValidators: Validator[] = [];
@@ -591,14 +596,37 @@ export class ValidationService {
591596
* @param form
592597
* @param callback
593598
*/
594-
validateForm = (form: HTMLFormElement, callback: Function) => {
599+
validateForm = (form: HTMLFormElement, callback?: ValidatedCallback) => {
595600
let formUID = this.getElementUID(form);
596601
let formValidationEvent = this.elementEvents[formUID];
597602
if (formValidationEvent) {
598-
formValidationEvent(null, callback);
603+
formValidationEvent(undefined, callback);
599604
}
600605
}
601606

607+
/**
608+
* Handler for validated form submit events.
609+
* Default calls `submitValidForm(form)` on success
610+
* and `focusFirstInvalid(form)` on failure.
611+
* @param form The form that has been validated.
612+
* @param success The validation result.
613+
*/
614+
handleValidated = (form: HTMLFormElement, success: boolean) => {
615+
if (success) {
616+
this.submitValidForm(form);
617+
}
618+
else {
619+
this.focusFirstInvalid(form);
620+
}
621+
}
622+
623+
/**
624+
* Calls `requestSubmit()` on the provided form.
625+
* @param form The validated form to submit
626+
*/
627+
submitValidForm = (form: HTMLFormElement) => {
628+
form.requestSubmit();
629+
}
602630

603631
/**
604632
* Focuses the first invalid element within the provided form
@@ -624,7 +652,7 @@ export class ValidationService {
624652
* @param callback
625653
* @returns
626654
*/
627-
isValid = (form: HTMLFormElement, prevalidate: boolean = true, callback: Function) => {
655+
isValid = (form: HTMLFormElement, prevalidate: boolean = true, callback?: ValidatedCallback) => {
628656
if (prevalidate) {
629657
this.validateForm(form, callback);
630658
}
@@ -641,7 +669,7 @@ export class ValidationService {
641669
* @param callback
642670
* @returns
643671
*/
644-
isFieldValid = (field: HTMLElement, prevalidate: boolean = true, callback: Function) => {
672+
isFieldValid = (field: HTMLElement, prevalidate: boolean = true, callback?: ValidatedCallback) => {
645673

646674
if (prevalidate) {
647675
let form = field.closest("form");
@@ -658,9 +686,9 @@ export class ValidationService {
658686
* Returns true if the event triggering the form submission indicates we should validate the form.
659687
* @param e
660688
*/
661-
private shouldValidate(e: Event) {
689+
private shouldValidate(e?: Event) {
662690
// Skip client-side validation if the form has been submitted via a button that has the "formnovalidate" attribute.
663-
return !(e !== null && e['submitter'] && e['submitter']['formNoValidate']);
691+
return !(e && e['submitter'] && e['submitter']['formNoValidate']);
664692
}
665693

666694
/**
@@ -686,7 +714,7 @@ export class ValidationService {
686714
}
687715

688716
let validating = false;
689-
let cb = (e: Event, callback?: Function) => {
717+
let cb = (e?: Event, callback?: ValidatedCallback) => {
690718
// Prevent recursion
691719
if (validating) {
692720
return;
@@ -712,36 +740,18 @@ export class ValidationService {
712740

713741
validate.then(success => {
714742
this.logger.log('Validated (success = %s)', success, form);
715-
let isProgrammaticValidate = !e;
716-
if (success) {
717-
if (isProgrammaticValidate) {
718-
callback(true);
719-
return;
720-
}
721-
const validationEvent = new CustomEvent('validation',
722-
{
723-
detail: { valid: true }
724-
});
725-
form.dispatchEvent(validationEvent);
726-
727-
//Resubmit the form here, after the async validation is completed.
728-
form.requestSubmit();
729-
743+
if (callback) {
744+
callback(success);
730745
return;
731746
}
732747

733748
const validationEvent = new CustomEvent('validation',
734749
{
735-
detail: { valid: false }
750+
detail: { valid: success }
736751
});
737752
form.dispatchEvent(validationEvent);
738753

739-
if (isProgrammaticValidate) {
740-
callback(false);
741-
}
742-
else {
743-
this.focusFirstInvalid(form);
744-
}
754+
this.handleValidated(form, success);
745755
}).catch(error => {
746756
this.logger.log('Validation error', error);
747757
}).finally(() => {

types/index.d.ts

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,10 @@ export declare type ValidationDirective = {
3232
* Promise return signifies asynchronous plugin behavior, with same behavior as Boolean or String.
3333
*/
3434
export declare type ValidationProvider = (value: string, element: HTMLInputElement, params: StringKeyValuePair) => boolean | string | Promise<boolean | string>;
35+
/**
36+
* Callback to receive the result of validating a form.
37+
*/
38+
export declare type ValidatedCallback = (success: boolean) => void;
3539
/**
3640
* Contains default implementations for ASP.NET Core MVC validation attributes.
3741
*/
@@ -167,7 +171,20 @@ export declare class ValidationService {
167171
* @param form
168172
* @param callback
169173
*/
170-
validateForm: (form: HTMLFormElement, callback: Function) => void;
174+
validateForm: (form: HTMLFormElement, callback?: ValidatedCallback) => void;
175+
/**
176+
* Handler for validated form submit events.
177+
* Default calls `submitValidForm(form)` on success
178+
* and `focusFirstInvalid(form)` on failure.
179+
* @param form The form that has been validated.
180+
* @param success The validation result.
181+
*/
182+
handleValidated: (form: HTMLFormElement, success: boolean) => void;
183+
/**
184+
* Calls `requestSubmit()` on the provided form.
185+
* @param form The validated form to submit
186+
*/
187+
submitValidForm: (form: HTMLFormElement) => void;
171188
/**
172189
* Focuses the first invalid element within the provided form
173190
* @param form
@@ -180,15 +197,15 @@ export declare class ValidationService {
180197
* @param callback
181198
* @returns
182199
*/
183-
isValid: (form: HTMLFormElement, prevalidate: boolean, callback: Function) => boolean;
200+
isValid: (form: HTMLFormElement, prevalidate?: boolean, callback?: ValidatedCallback) => boolean;
184201
/**
185202
* 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
186203
* @param form
187204
* @param prevalidate
188205
* @param callback
189206
* @returns
190207
*/
191-
isFieldValid: (field: HTMLElement, prevalidate: boolean, callback: Function) => boolean;
208+
isFieldValid: (field: HTMLElement, prevalidate?: boolean, callback?: ValidatedCallback) => boolean;
192209
/**
193210
* Returns true if the event triggering the form submission indicates we should validate the form.
194211
* @param e

0 commit comments

Comments
 (0)