首页 > 解决方案 > Angular 7:Formvalidation,Validators.pattern 不起作用

问题描述

我需要一个来自仅匹配整数的验证。因此我使用pattern带有正则表达式的验证器(见下文)。此外,该字段不应为空,因此我添加了required验证器。

但是pattern永远不会触发错误。我阅读了角度文档并查看了源代码,pattern但对我来说仍然没有意义。此外,我已经阅读了与该主题相关的几乎所有关于 stackoverflow 的问题。但我仍然无法弄清楚为什么该模式不起作用。

或许有人能帮帮我,谢谢!

这是我的代码component.ts:

// definition of the formcontrol
hours = new FormControl('', [
  Validators.required,
  Validators.pattern('^[0-9]*$'),
])

// for debugging
log() {
  console.log('required: ', this.hours.hasError('required'));
  console.log('pattern: ', this.hours.hasError('pattern'));
  console.log('Erros: ', this.hours.errors);
}

模板:

<mat-form-field>
  <input matInput [formControl]="hours" (input)="log()"
    placeholder="Anzahl der ausbezahlten Überstunden" type="number">
  <mat-error *ngIf="hours.hasError('required') && !hours.hasError('pattern')">
    Anzahl der Überstunden fehlt!
  </mat-error>
  <mat-error *ngIf="!hours.hasError('required') && hours.hasError('pattern')">
    Anzahl muss eine Ganzzahl sein!
  </mat-error>
</mat-form-field>

例子inputValue=""

required: true
pattern: false
Error: Object { required: true }

inputValue="1"

required:  false
pattern:  false
Error:  null

inputValue="a"

required:  true
pattern:  false
Error: Object { required: true }

标签: angulartypescriptangular7angular-reactive-forms

解决方案


它不适用于 type="number",如果将其更改为 type="text" 它将起作用


推荐阅读