繁体   English   中英

如何创建只接受数字的 Validator.pattern

[英]How to create a Validator.pattern that accepts ONLY numbers

我正在做一个有角度的项目,我试图确保输入字段只接受 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()检查是否以可接受的格式以及各种长度验证器输入了类似的东西。

您也许可以使用自定义验证器,像这样

// 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>

下面的验证器只有数字。 试试这个,它可能有效: ^[0-9]*$

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM