【发布时间】:2019-09-23 09:13:43
【问题描述】:
我在用户键入时更新输入时遇到问题。
我需要从用户那里获取如下所示的代码:354e-fab4(2 个字母数字组,每组 4 个字符,用“-”分隔)。用户不应该键入'-',它会自动插入。 当用户键入的内容与用于验证的正则表达式不匹配时,我想恢复到以前的有效值。
问题是验证失败时输入中的值没有正确更新。另一方面,如果我设置了一个硬编码字符串,则该值会反映在输入中。
我在 stackblitz 中隔离了问题:https://stackblitz.com/edit/angular-qsbtiz
您可以通过输入超过 8 个字符来重现该问题:正则表达式测试失败,代码设置为之前的值,但该值未反映在 HTML 输入中。
这是当输入值改变时调用的方法:
onCodeChange(newValue: string) {
const previousValue = this.code;
this.code = newValue;
const regex = new RegExp(/^([a-z0-9]{0,4})?(-)?([a-z0-9]{0,4})?(-)?$/);
// If the code doesn't match the regex, revert to the old value and return.
if (!regex.test(newValue)) {
// This changes this.code, but it's not reflected in the input's value.
this.code = previousValue;
// This changes this.code and it is reflected in the input's value.
//this.code = '1234';
} else {
const groups = regex.exec(newValue);
if (!groups[2] && groups[3]) {
this.code = `${groups[1]}-${groups[3]}`;
}
}
}
请注意,我对这段代码有什么问题感兴趣,而不是对使用自定义屏蔽输入组件等替代解决方案感兴趣。
谢谢。
【问题讨论】:
标签: javascript angular