Angular 7:表单验证,Validators.pattern 不工作

Angular 7: Formvalidation, Validators.pattern not working

我只需要对匹配的整数进行验证。因此,我将 patternvalidator 与正则表达式一起使用(见下文)。此外,该字段不应为空,因此我添加了 required 验证器。

但从未触发 pattern 错误。我阅读了 angular 文档并查看了 pattern 的源代码,但它对我来说仍然毫无意义。此外,我已经阅读了几乎所有与该主题相关的关于 Whosebug 的问题。但是我还是不明白为什么这个模式不起作用。

也许你们中的一些人可以帮助我,谢谢!

这是我的代码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 }

来自 documentation required() 的类型为 ValidationErrors,而您正在尝试使用 constructor(any, ValidatorFn[]).

创建 FormControl

您尝试过使用 Validators.compose([Validators.pattern('^[0-9]*$'), Validators.required]) 吗?

Validators.compose() returns 一个可用于创建 FormControl 的 ValidatorFn。

你可以检查这个 for an example and a working example here

尝试这种方式,通常我在这里使用 formBuilder

组件

 this.form = fb.group({
    age:[null , [Validators.required , Validators.pattern('[0-9]*')]]
  })

模板

<ng-container *ngIf="form.get('age').invalid && (form.get('age').touched || form.get('age').dirty)">
  <div *ngIf="form.get('age').hasError('required')">
    Required...
  </div>
  <div *ngIf="form.get('age').hasError('pattern')">
    Pattern Not valid
  </div>
</ng-container>

stackblitz demo

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