Skip to content

Commit

Permalink
Merge pull request #6 from skttl/focus-first-invalid
Browse files Browse the repository at this point in the history
Adds method for focusing first invalid field upon validation.
  • Loading branch information
haacked authored Nov 18, 2021
2 parents cef508d + b0187a4 commit fbde6cd
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -602,6 +602,24 @@ export class ValidationService {
}
}


/**
* 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();
}
}
}

/**
* Tracks a <form> element as parent of an input UID. When the form is submitted, attempts to validate the said input asynchronously.
* @param form
Expand Down Expand Up @@ -648,9 +666,14 @@ export class ValidationService {
detail: { valid: false }
});
form.dispatchEvent(validationEvent);


if (isProgrammaticValidate) {
callback(false);
}
else {
this.focusFirstInvalid(form);
}
}).catch(error => {
console.log(error);
});
Expand Down

0 comments on commit fbde6cd

Please sign in to comment.