CustomValidator仅调用一次

时间:2019-02-13 06:34:24

标签: angular formgroups

我有一个表单控件:

我尝试了2种不同的方式

    this.passwordForm = new FormGroup({
        oldPassword: new FormControl(),
        newPassword: new FormControl(),
        confirmationPassword: new FormControl()
    })
    this.passwordForm.get("confirmationPassword").setValidators(this.CheckInputMatchValidator("newPassword","confirmationPassword"))

    this.passwordForm = new FormGroup({
        oldPassword: new FormControl(),
        newPassword: new FormControl(),
        confirmationPassword: new FormControl()
    })
    this.passwordForm.setValidators(this.CheckInputMatchValidator("newPassword","confirmationPassword"));

我有功能

CheckInputMatchValidator(control1: string, control2: string){
    console.log(this.passwordForm.get(control1).value , this.passwordForm.get(control2).value)
    if(this.passwordForm.get(control1).value != this.passwordForm.get(control2).value){
        console.log("ok")
        this.passwordForm.get(control2).setErrors({notMatching: true});
    } else {
        this.passwordForm.get(control2).setErrors(null);
    }
    return null;
}

模板

<mat-form-field class="full-width">
  <input matInput type="password" placeholder="{{ 'UPDATE_PASSWORD_PANEL.CONFIRM_PASSWORD' | translate }}" formControlName="confirmationPassword" required>
</mat-form-field>
<div *ngIf="passwordForm?.controls.confirmationPassword?.invalid && (passwordForm?.controls.confirmationPassword?.dirty || passwordForm?.controls.confirmationPassword?.touched)" class="alert alert-danger">
    <div *ngIf="passwordForm?.controls.confirmationPassword?.errors?.required">
        {{'INPUT_ERR.REQUIRED' | translate}}
    </div>
    <div *ngIf="passwordForm?.controls.confirmationPassword?.errors?.notMatching">
        {{'INPUT_ERR.INVALID_CONFIRM_PASSWORD' | translate}}
    </div>
</div>

,但是CheckInputMatchValidator仅在创建时调用,而不是在每次输入更改时调用。我想念什么?该日志仅出现一次。

1 个答案:

答案 0 :(得分:1)

如下所示更新CheckInputMatchValidator函数将起作用。

CheckInputMatchValidator(control1: string, control2: string): ValidatorFn {
     return (control: AbstractControl): { [key: string]: boolean } | null => {
        if(this.passwordForm.get(control1).value != this.passwordForm.get(control2).value){
            this.passwordForm.get(control2).setErrors({notMatching: true});
            return {notMatching: true};
        } else {
            this.passwordForm.get(control2).setErrors(null);
        }
        return null;
     }
}
相关问题