@@ -387,6 +387,8 @@ export abstract class TextField extends textFieldBaseClass {
387
387
private readonly leadingIcons ! : Element [ ] ;
388
388
@queryAssignedElements ( { slot : 'trailing-icon' } )
389
389
private readonly trailingIcons ! : Element [ ] ;
390
+ private isCheckingValidity = false ;
391
+ private isReportingValidity = false ;
390
392
// Needed for Safari, see https://bugs.webkit.org/show_bug.cgi?id=261432
391
393
// Replace with this[internals].validity.customError when resolved.
392
394
private hasCustomValidityError = false ;
@@ -402,8 +404,11 @@ export abstract class TextField extends textFieldBaseClass {
402
404
* @return true if the text field is valid, or false if not.
403
405
*/
404
406
checkValidity ( ) {
407
+ this . isCheckingValidity = true ;
405
408
this . syncValidity ( ) ;
406
- return this [ internals ] . checkValidity ( ) ;
409
+ const isValid = this [ internals ] . checkValidity ( ) ;
410
+ this . isCheckingValidity = false ;
411
+ return isValid ;
407
412
}
408
413
409
414
/**
@@ -425,6 +430,7 @@ export abstract class TextField extends textFieldBaseClass {
425
430
* @return true if the text field is valid, or false if not.
426
431
*/
427
432
reportValidity ( ) {
433
+ this . isReportingValidity = true ;
428
434
let invalidEvent : Event | undefined ;
429
435
this . addEventListener (
430
436
'invalid' ,
@@ -435,6 +441,14 @@ export abstract class TextField extends textFieldBaseClass {
435
441
) ;
436
442
437
443
const valid = this . checkValidity ( ) ;
444
+ this . showErrorMessage ( valid , invalidEvent ) ;
445
+
446
+ this . isReportingValidity = false ;
447
+
448
+ return valid ;
449
+ }
450
+
451
+ private showErrorMessage ( valid : boolean , invalidEvent : Event | undefined ) {
438
452
if ( invalidEvent ?. defaultPrevented ) {
439
453
return valid ;
440
454
}
@@ -825,6 +839,26 @@ export abstract class TextField extends textFieldBaseClass {
825
839
this . hasTrailingIcon = this . trailingIcons . length > 0 ;
826
840
}
827
841
842
+ private readonly onInvalid = ( invalidEvent : Event ) => {
843
+ if ( this . isCheckingValidity || this . isReportingValidity ) {
844
+ return ;
845
+ }
846
+
847
+ this . showErrorMessage ( false , invalidEvent ) ;
848
+ } ;
849
+
850
+ override connectedCallback ( ) {
851
+ super . connectedCallback ( ) ;
852
+
853
+ // Handles the case where the user submits the form and native validation
854
+ // error pops up. We want the error styles to show.
855
+ this . addEventListener ( 'invalid' , this . onInvalid ) ;
856
+ }
857
+
858
+ override disconnectedCallback ( ) {
859
+ super . disconnectedCallback ( ) ;
860
+ this . removeEventListener ( 'invalid' , this . onInvalid ) ;
861
+ }
828
862
// Writable mixin properties for lit-html binding, needed for lit-analyzer
829
863
declare disabled : boolean ;
830
864
declare name : string ;
0 commit comments