CustomValidator вызывается только один раз - PullRequest
0 голосов
/ 13 февраля 2019

У меня есть элемент управления формы:

Я пробовал 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;
}

template

<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 голосов
/ 13 февраля 2019

Обновите функцию 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;
     }
}
...