通过valueAccessor.writeValue()设置值后,Formcontrol无效状态保持不变 [英] Formcontrol invalid state unchanged after setting value via valueAccessor.writeValue()

查看:86
本文介绍了通过valueAccessor.writeValue()设置值后,Formcontrol无效状态保持不变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在formcontrol上设置了Validators.pattern()来验证是否输入了正确的电话号码.我还向项目添加了一个属性指令,以屏蔽以下格式的电话号码输入-123/456-7890.该指令强制执行掩码,并通过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().

输入有效的电话号码后,表单控件的无效状态为false,表示输入内容与模式匹配.但是,如果用户尝试输入另一个字符,而该指令阻止显示其他输入,则控件上的无效状态为true.这会使用户感到困惑,因为他们看到一个有效的电话号码,但是直到他们退格并重新输入一个号码后,该控件才会生效.

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 - https://angular6-phone-mask-uytj4e.stackblitz.io

Stackblitz编辑器- https://stackblitz.com/edit/angular6-phone-mask-uytj4e

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

要复制,请输入10位数字.您应该看到控件周围的红色边框消失了.然后输入第11位数字(或任何字符).尽管没有显示其他文本,您仍将看到控件周围的边框再次变为红色.

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.

我知道上述解决方法是在输入中设置maxlength属性.但是我仍然很好奇如何解决根本问题.

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.

推荐答案

您可以尝试

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

代替此

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

这可以解决您的问题,但这不是最佳解决方案.

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

这篇关于通过valueAccessor.writeValue()设置值后,Formcontrol无效状态保持不变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆