Mena
Mena

Reputation: 2029

How to display custom validations errors in Angular 7

I want to display a red border round the input field of a form and the message Password is invalid and when a user types in a password that doesn't match what the password has been set to.

I can see the red border indicating that there is an error when I type something different from the set password but the message is not displayed. I haven't been able to figure out what the problem is after spending several hours going through my code so kindly look at my code and point me to the bug

password.validators.ts

import { AbstractControl, ValidationErrors } from "@angular/forms";

export class PasswordValidators {
    static matchOldPassword(
       control: AbstractControl
       ): Promise<ValidationErrors | null> {
       return new Promise((resolve, reject) => {
           setTimeout(() => {
           if (control.value !== "1234") resolve({ matchOldPassword: true });
           else resolve(null);
           }, 2000);
       });
   }
}

password-change.component.ts

import { PasswordValidators } from "./password.validator";
import { FormGroup, FormControl, Validators } from "@angular/forms";
import { Component } from "@angular/core";

@Component({
  selector: "password-change",
  templateUrl: "./password-change.component.html",
  styleUrls: ["./password-change.component.css"]
})
export class PasswordChangeComponent {
  form = new FormGroup({
    oldPassword: new FormControl(
    "",
    Validators.required,
    PasswordValidators.matchOldPassword
    )
  });
}

password-change.component.html

<form [formGroup]="form">
<div class="form-group">
<label for="oldPassword" class="font-weight-bold">Old Password</label>
<input
  formControlName="oldPassword"
  type="password"
  id="oldPassword"
  class="form-control"
/>
<div
  *ngIf="oldPassword.touched && oldPassword.pristine"
  class="text-danger"
>
  <div *ngIf="oldPassword.errors.required">Old password is required.</div>
  <div *ngIf="oldPassword.errors.matchOldPassword">
    Old password is not valid.
  </div>
</div>
</div>
</form>

Upvotes: 1

Views: 259

Answers (1)

AVJT82
AVJT82

Reputation: 73387

Remove oldPassword.pristine from your wrapping div. Your if becomes falsy after the field has been modified, since it's no longer pristine, so the whole div won't show. Else, your code looks fine! So your wrapping div should just look like:

<div *ngIf="oldPassword.touched">

StackBlitz

Upvotes: 1

Related Questions