【问题标题】:How to create a Validator.pattern that accepts ONLY numbers如何创建仅接受数字的 Validator.pattern
【发布时间】:2021-10-22 04:33:08
【问题描述】:

我正在做一个角度项目,我试图确保输入字段只接受 1 到 28 之间的正整数,但是我尝试过的正则表达式在输入字母时不会将表单字段标记为无效。

这是我的代码:

setDateRegex = /^[0-9]*$/;

. . . 

scheduleSetDaysBefore: [null, [Validators.max(28), Validators.min(1), Validators.pattern(this.setDateRegex)]],

我也尝试了以下正则表达式,但都不起作用。

/^[0-9]+$/

/^[0-9]+(\.?[0-9]+)?$/

还有一些我不记得了。

编辑

我只是想补充一下,我已经通过使用Valdidator.pattern() 来检查是否以可接受的格式输入了电子邮件以及各种长度验证器,从而实现了类似的效果。

【问题讨论】:

  • this post 还有更多,没有任何作用吗?

标签: angular regex typescript validation customvalidator


【解决方案1】:

你可以使用custom validator,类似这样的

// i have multiple custom validators so I am using them in a separate file.
export class CustomValidators {

  static isNumbers(control: AbstractControl) {

    if (!(control.value)) {
      return null;
    }

    return String(control.value)
      .match(/^[0-9.]+$/) ? null : {'isNumbers': true};
  }
}

在你的 formBuilder 中,包含这个

scheduleSetDaysBefore: [null, [Validators.max(28), Validators.min(1), CustomValidators.isNumbers]],

在您的 HTML 中,您可以检查此错误,可能在控件上应用无效类或显示消息

<span class="error-message" *ngIf="form.get('scheduleSetDaysBefore').getError('isNumbers')">Please enter numbers only.</span>

【讨论】:

    猜你喜欢
    • 2023-03-20
    • 2011-01-22
    • 2014-08-24
    • 2020-03-03
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多