Crocsx
Crocsx

Reputation: 7640

CustomValidator only called once

I have a form control :

I tried 2 different ways

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

and

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

There I have the function

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>

but the CheckInputMatchValidator is only called when I create it, and not every time the input changes. What I am missing ? The log appear only one time.

Upvotes: 0

Views: 227

Answers (1)

Hardik Patel
Hardik Patel

Reputation: 3959

Update CheckInputMatchValidator function as below would work.

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;
     }
}

Upvotes: 1

Related Questions