From 76c1ff27c0d58d50650680210bb9344603002a24 Mon Sep 17 00:00:00 2001 From: Elliott Marquez Date: Fri, 20 Oct 2023 16:52:23 -0700 Subject: [PATCH] fix(select,textfield): native form validation shows error state PiperOrigin-RevId: 575349644 --- select/internal/select.ts | 34 ++++++++++++++++++++++++++++++-- textfield/internal/text-field.ts | 30 +++++++++++++++++++++++++++- 2 files changed, 61 insertions(+), 3 deletions(-) diff --git a/select/internal/select.ts b/select/internal/select.ts index 937ec628a52..9a4b3b30aed 100644 --- a/select/internal/select.ts +++ b/select/internal/select.ts @@ -258,6 +258,8 @@ export abstract class Select extends LitElement { @query('#label') private readonly labelEl!: HTMLElement; @queryAssignedElements({slot: 'leading-icon', flatten: true}) private readonly leadingIcons!: Element[]; + private isCheckingValidity = false; + private isReportingValidity = false; private customValidationMessage = ''; private readonly internals = (this as HTMLElement /* needed for closure */).attachInternals(); @@ -308,8 +310,11 @@ export abstract class Select extends LitElement { * @return true if the select is valid, or false if not. */ checkValidity() { + this.isCheckingValidity = true; this.syncValidity(); - return this.internals.checkValidity(); + const isValid = this.internals.checkValidity(); + this.isCheckingValidity = false; + return isValid; } /** @@ -329,12 +334,21 @@ export abstract class Select extends LitElement { * @return true if the select is valid, or false if not. */ reportValidity() { + this.isReportingValidity = true; let invalidEvent: Event|undefined; this.addEventListener('invalid', event => { invalidEvent = event; }, {once: true}); const valid = this.checkValidity(); + this.showErrorMessage(valid, invalidEvent); + + this.isReportingValidity = false; + + return valid; + } + + private showErrorMessage(valid: boolean, invalidEvent: Event|undefined) { if (invalidEvent?.defaultPrevented) { return valid; } @@ -801,7 +815,9 @@ export abstract class Select extends LitElement { const validationMessage = this.customValidationMessage || valueMissing && this.getRequiredValidationMessage() || ''; - this.internals.setValidity({valueMissing, customError}, validationMessage); + this.internals.setValidity( + {valueMissing, customError}, validationMessage, + this.field ?? undefined); } // Returns the platform `