失去焦点时的验证错误

时间:2019-07-01 19:41:31

标签: angular validation angular-reactive-forms

我有一个角反应形式

html文件

                    <mat-form-field>
                        <input formControlName="addressNumber" matInput type="number" [placeholder]="addressNumber"/>
                    </mat-form-field>
                    <div *ngIf="errorMessage" class="warnColorText">{{errorMessage}}</div>

ts文件

           this.editForm = this.fb.group({
            addressNumber: [0, [
            Validators.required,
            this.formValidation.customMinMaxValidation(2, 256)
        ]],
         ...});

初始化表单后,我还具有在ts文件中添加异步验证器的代码。

this.editForm.get('addressNumber').setAsyncValidators([this.formValidation.uniqueNumberValidation()]);

一切正常。如果数字不是唯一的,则表格将显示错误。但是,如果该字段失去焦点,该错误就会消失。当视野不清晰时,什么会导致错误消失?

2 个答案:

答案 0 :(得分:1)

您可以绑定errorMessage进行自定义验证,并通过@ rxweb / reactive-form-validators直接在HTML中使用,您需要在自定义验证器中声明自定义验证,如下所示:

 addressNumber:['',RxwebValidators.compose({validators:[this.uniqueNumberValidation()]})]

根据此示例,如果在addressNumber中添加1,将显示errorMessage。

组件ts:

import { Component, OnInit, } from '@angular/core';
import { FormGroup,AbstractControl } from "@angular/forms"
import { RxFormBuilder,RxwebValidators } from '@rxweb/reactive-form-validators';

@Component({
    selector: 'app-compose-validators',
    templateUrl: './compose-validators.component.html'
})
export class ComposeValidatorsComponent implements OnInit {
    userFormGroup: FormGroup

    constructor(
        private formBuilder: RxFormBuilder    ) { }

    ngOnInit() {

        this.userFormGroup = this.formBuilder.group({
          addressNumber:['',RxwebValidators.compose({validators:[this.uniqueNumberValidation()]})]
        });
    }
     uniqueNumberValidation() {
  return (control: AbstractControl) => {
        if (control.value != 1)
            return null;
        else
            return {
                'addressNumber': { message: "Address Number Should be Unique" }
            };
    }
}
}
<div>
  <form [formGroup]="userFormGroup">
    <div class="form-group">
      <label>Address Number</label>
      <input type="text" formControlName="addressNumber" class="form-control" />
      <small class="form-text text-danger" *ngIf="userFormGroup.controls.addressNumber.errors">{{userFormGroup.controls.addressNumber.errorMessage}}<br /></small>
    </div>
    <button [disabled]="!userFormGroup.valid" class="btn btn-primary">Submit</button>
  </form>
</div>

Stackblitz Example

答案 1 :(得分:0)

您是否使用角形材料?我认为是这样,从您提供的html开始。

您是否尝试在<mat-form-field>标签内添加错误消息? 就像他们的文档{@ https://material.angular.io/components/form-field/overview#error-messages

例如

  <mat-form-field>
    <input formControlName="addressNumber" matInput type="number [placeholder]="addressNumber"/>
    <mat-error *ngIf="addressNumber.invalid">{{errorMessage}}</mat-error>
  </mat-form-field>