You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 14正则验证器模式匹配异常问题排查

Angular 14正则验证器模式匹配异常求助

问题背景

我基于Angular 14开发了一款支持多种文本输入类型的动态文本组件,可按需添加自定义模式验证。其中type=monetary类型的文本框配置代码如下:

case InputType.Monetary:
  response.icon = response.icon ?? 'attach_money-outlined';
  response.iconPosition = response.iconPosition ?? LayoutPositions.Left;
  response.placeholder = response.placeholder ?? '0.00';
  response.validationPattern = response.validationPattern ?? /^(\d{1,3}(,\d{3})*|(\d+))(.\d{2})?$/gm;
  response.patternErrorText = response.patternErrorText ?? 'Please enter a valid dollar amount';
  response.mask = response.mask ?? this.currencyInputMask;
  break;

验证规则应用逻辑

组件内通过以下方式为表单控件设置验证规则:

if (response?.validationPattern) {
  this.form.get(response.responseId)?.setValidators(Validators.pattern(response.validationPattern));
}

异常表现

当前遇到的问题:当文本框输入字符数为偶数时,无论内容是否符合规则,均会显示验证无效;输入字符数为奇数时,验证逻辑正常工作。已单独验证正则表达式本身,确认其逻辑无问题。

  • 无效状态(UI):输入偶数长度内容时,UI展示错误提示
  • 无效状态(后端):对应表单控件的后端验证标记为无效
  • 有效状态(UI):输入奇数长度内容时,UI无错误提示
  • 有效状态(后端):对应表单控件的后端验证标记为有效

已尝试的解决方案(均未解决问题)

  • 替换为其他正则表达式进行测试
  • 将正则表达式改为字符串类型传入验证器
  • 直接在setValidators中写入正则表达式,而非通过变量传递

内容的提问来源于stack exchange,提问作者ChungWu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 11:22:10