Nick Silberstein
Nick Silberstein

Reputation: 833

Formcontrol invalid state unchanged after setting value via valueAccessor.writeValue()

I have a Validators.pattern() set on the formcontrol to validate that a correct phone number has been input. I've also added an attribute directive to my project to mask phone number input in the following format -- 123/456-7890. The directive enforces the mask, and sets the value via valueAccessor.writeValue().

After entering a valid phone number, the form control invalid state is false, meaning the input matches the pattern. However, if the user tries to input another character, while the directive prevents the additional input from being displayed, the invalid state on the control is true. This makes it confusing for the user, where they see a valid phone number, but until they backspace and re-enter a number, the control doesn't validate.

Stackblitz - https://angular6-phone-mask-uytj4e.stackblitz.io

Stackblitz Editor - https://stackblitz.com/edit/angular6-phone-mask-uytj4e

To reproduce, enter 10 digits. You should see the red border around the control disappear. Then enter an 11th digit (or any character). You'll see the border around the control turn red again, despite no additional text being displayed.

I'm aware that a quick fix for the above is to set a maxlength property on the input. But I'm still curious how to fix the root problem.

Upvotes: 0

Views: 287

Answers (1)

tufonas
tufonas

Reputation: 313

You can try this

phone:['', Validators.pattern('^[0-9]{3}/[0-9]{3}-[0-9]{4,5}')]

instead of this

phone:['', Validators.pattern('^[0-9]{3}/[0-9]{3}-[0-9]{4}')]

This will fix your problem but it is not the best solution.

Upvotes: 1

Related Questions