angular 表单控件需要验证器仅在表单输入时有效

angular form control required validator only works when their is form input

我有一个带有嵌套表单组的反应式表单,其中一些表单控件需要验证器。

似乎只有当用户在表单中输入值时才会进行验证。如果 提交表单时没有用户交互,带有所需验证器的空文本框显示为有效。 这是 angular 表单的正常行为吗?我错过了什么吗?

谢谢

皮特

html 模板:

<form [formGroup]="ticketMarkForm" (ngSubmit)="submitTicket()">
  ..
   <div formGroupName ="systemForm">
     <mat-form-field appearance="outline">
      <mat-label>Pipe Length (Ft):</mat-label>
      <input matInput type="number" required formControlName="pipeLength">
     </mat-form-field>
</div>
 ..
 <button type="submit" mat-stroked-button>Submit</button>
</form>

组件打字稿:

export class MtMarkFormComponent implements OnInit {
..
ticketMarkForm: FormGroup;
...
constructor(private checkService: MTMarkFormCheckService) { }
 ngOnInit(): void {
 //forms
 this.ticketMarkForm = new FormGroup({
  systemForm: new FormGroup({
    ...
   pipeDiameter: new FormControl(Validators.required),
   ...
  })
  });

}
submitTicket() {
   let pipeDiam:any=this.ticketMarkForm.get('systemForm').get('pipeDiameter');
   this.checkService.CheckRequiredValid(pipeDiam);
   }
}

检查表单打字稿的服务:

export class MTMarkFormCheckService {
 CheckRequiredValid(fc: FormControl) {
        if (fc.invalid) {//if the control is left blank/untouched evaluates to valid.  I've also 
  tried to mark the control as dirty (fc.markAsDirty()) but same result
            alert("invalid");
         }
         else {
           alert("valid");
        }
 }

这是默认的 Angular 行为。您必须像这样定义自定义错误状态匹配器。

import {FormControl, FormGroupDirective, NgForm} from '@angular/forms';
import {ErrorStateMatcher} from '@angular/material/core';

export class CustomErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null | undefined, form: FormGroupDirective | NgForm | null): boolean {
    if (control == null) {
      return false;
    }
    return control.invalid;
  }
}

ts :

export class MtMarkFormComponent implements OnInit {
   :
  public esm = new CustomErrorStateMatcher();
   :
}

html :

<input matInput type="number" required formControlName="pipeLength" [errorStateMatcher]="esm">

这个说法不是很清楚但是会尝试探讨

empty textboxes with a required validator show as valid

我已经尝试复制您在 this Stackblitz demo 中描述的问题,但我得到了不同的结论。

Empty textboxes with required validators will be return false for the valid property

请务必注意,在表单被触摸之前,表单上的验证不会显示

在演示中我注释掉了行// this.ticketMarkForm.markAllAsTouched()。如果取消注释,验证将显示在表单上

默认情况下 angular 将调用 (ngSubmit)='someFunction()'(请参阅 Angularjs prevent form submission when input validation fails)但表单状态将无效。

如果您尝试在 demo 中提交表单,您会注意到控制台日志显示 false