Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 force custom validation on keyup

I have this code:

this.form = fb.group({
        username: ['', Validators.compose([Validators.required])],
        fullName: ['', Validators.compose([Validators.required])],
        password: ['', Validators.compose([Validators.required])],
        confirmPassword: ['', Validators.required],
    }, {validator: matchingPasswords('password', 'confirmPassword')});

matchingPasswords:

export function matchingPasswords(passwordKey: string, passwordConfirmationKey: string) {
return (group: FormGroup) => {
    let password = group.controls[passwordKey];
    let passwordConfirmation = group.controls[passwordConfirmationKey];
    if (password.value !== passwordConfirmation.value) {
        return passwordConfirmation.setErrors({mismatchedPasswords: true})
    }
}

}

html:

<div class="form-group">
        <input [formControl]="confirmPassword" class="form-control checking-field" type="password">
        <span class="help-block text-danger" *ngIf="form.get('password').touched && form.get('password').hasError('required')">
</div>
<div class="form-group">
        <input class="custom-control-input checkbox-main" type="checkbox" [(ngModel)]="policyButtonValue" [ngModelOptions]="{standalone: true}" ngDefaultControl>
        <span class="custom-control-indicator"></span>
</div>

this is functional, and works perfectly, but I have a special use-case scenario that should be fixed.

  1. click in the first password field.
  2. fill up a password, eg.: "foo"
  3. click in the confirm password field.
  4. tpye in the same thing, eg.:"foo" enter image description here till this point, no problems.
  5. type something different into the confirm password field, eg: "foobar" (at this point, the validator shows that there is an error here) enter image description here
  6. click in the password field
  7. type in the same thing that is in the password field: "foobar" and here, the confirm password field is still invalid, until the password field looses focus... enter image description here is there a way, to force the matchingPassword validation run on keyup event, rather than how it works now?
like image 339
ForestG Avatar asked Mar 14 '17 10:03

ForestG


1 Answers

You need an else block:

if (password.value !== passwordConfirmation.value) {
    passwordConfirmation.setErrors({mismatchedPasswords: true})
}
else {
    passwordConfirmation.setErrors(null);
}
like image 144
pixelbits Avatar answered Sep 28 '22 22:09

pixelbits