Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add form element validation to key methods #85

Merged
merged 1 commit into from
Jan 2, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -723,6 +723,9 @@ export class ValidationService {
* @param callback Receives true or false indicating validity after all validation is complete.
*/
validateForm = (form: HTMLFormElement, callback?: ValidatedCallback) => {
if (!(form instanceof HTMLFormElement)) {
throw new Error('validateForm() can only be called on <form> elements');
}
let formUID = this.getElementUID(form);
let formValidationEvent = this.formEvents[formUID];
if (formValidationEvent) {
Expand Down Expand Up @@ -762,6 +765,9 @@ export class ValidationService {
* @param submitEvent The `SubmitEvent`.
*/
handleValidated = (form: HTMLFormElement, success: boolean, submitEvent?: SubmitEvent) => {
if (!(form instanceof HTMLFormElement)) {
throw new Error('handleValidated() can only be called on <form> elements');
}
if (success) {
if (submitEvent) {
this.submitValidForm(form, submitEvent);
Expand All @@ -782,6 +788,9 @@ export class ValidationService {
* @param submitEvent The `SubmitEvent`.
*/
submitValidForm = (form: HTMLFormElement, submitEvent: SubmitEvent) => {
if (!(form instanceof HTMLFormElement)) {
throw new Error('submitValidForm() can only be called on <form> elements');
}
const newEvent = new SubmitEvent('submit', submitEvent);
if (form.dispatchEvent(newEvent)) {
// Because the submitter is not propagated when calling
Expand All @@ -808,6 +817,9 @@ export class ValidationService {
* @param form
*/
focusFirstInvalid = (form: HTMLFormElement) => {
if (!(form instanceof HTMLFormElement)) {
throw new Error('focusFirstInvalid() can only be called on <form> elements');
}
let formUID = this.getElementUID(form);
let formInputUIDs = this.formInputs[formUID];
let invalidFormInputUIDs = formInputUIDs.filter(uid => this.summary[uid]);
Expand All @@ -829,6 +841,9 @@ export class ValidationService {
* @returns The current state of the form. May be inaccurate if any validation is asynchronous (e.g. remote); consider using `callback` instead.
*/
isValid = (form: HTMLFormElement, prevalidate: boolean = true, callback?: ValidatedCallback) => {
if (!(form instanceof HTMLFormElement)) {
throw new Error('isValid() can only be called on <form> elements');
}
if (prevalidate) {
this.validateForm(form, callback);
}
Expand Down