如何在表单提交时显示验证错误

时间:2019-10-19 12:00:19

标签: angular angular-material angular-formbuilder

我想在单击“提交”按钮时显示验证错误。我试图使用markAllAsTouched()函数,但是它不起作用。仅在触摸字段

后,才会比较错误

HTML:

     <ion-content >
       <div class="ion-text-center tab1-padding">
         <form [formGroup]="newCat" (ngSubmit)="logForm()">
            <mat-form-field appearance="outline" class="tab1-name-field">
              <mat-label>Nome*</mat-label>
            <input matInput #input  formControlName="name">
            <mat-error 
                   *ngIf="newCat.controls['name'].hasError('required')"> 
                    Campo obbligatorio</mat-error>
            </mat-form-field>
           <mat-form-field appearance="outline">
            <mat-label>Data di nascita*</mat-label>
            <input matInput [matDatepicker]="picker" 
              formControlName="birthday" readonly (click)="picker.open()">
               <mat-datepicker-toggle matSuffix [for]="picker"></mat- 
                 datepicker-toggle>
              <mat-datepicker touchUi #picker></mat-datepicker>
             <mat-error                 
            *ngIf="newCat.controls['birthday'].hasError('required')">Campo 
           obbligatorio</mat-error>
         </mat-form-field>

         <button ion-button type="submit" [disabled]="newCat.pristine || 
           newCat.invalid" class="btn btn-success" 
           (click)="validateFields()">Inserisci</button>
         </form>

        </div>
      </ion-content>

Ts:

     constructor(private formBuilder: FormBuilder) {
       this.newCat = this.formBuilder.group({
       name: ['', Validators.required],
       birthday: ['', Validators.required],
     });
     }

      validateFields() {
        this.newCat.markAllAsTouched();
         this.newCat.markAllAsTouched();
       }

1 个答案:

答案 0 :(得分:1)

尝试遍历所有控件,并按如下所示制作单个控件,

validateFields(){
   this.validateAllFormFields(this.newCat);
}

validateAllFormFields(formGroup: FormGroup) {         
  Object.keys(formGroup.controls).forEach(field => {  
    const control = formGroup.get(field);             
    if (control instanceof FormControl) {             
      control.markAsTouched({ onlySelf: true });
    } 
  });
}