In my Angular 13 project, I have a change password form in which I want to show passwords must match error whenever user has touched confirmPassword field and written something in it. So the condition for showing the error should be something like this:
confirmPasswordis touchedconfirmPasswordis dirtyconfirmPasswordmatchednewPassword
out of the conditions above, I've only been able to implement number 3 and for the life of me, can't figure out how to add the other two conditions. Something must have changed in Angular 13 because all of the solutions I knew that used to work in previous versions are now failing.
This is where I'm at right now:
change-password.component.html
<div class="panel__input--field">
<input
name="new-password"
formControlName="newPassword"
/>
</div>
<div class="panel__input--field">
<input
name="confirm-password"
formControlName="confirmPassword"
/>
</div>
<mat-error *ngIf="changePasswordForm.errors?.['notMatched']">
passwords don't match
</mat-error>
change-password.component.ts
changePasswordForm: FormGroup;
constructor(private _formBuilder: FormBuilder) {
this.changePasswordForm = this._formBuilder.group(
{
currentPassword: ['', Validators.required],
newPassword: ['', Validators.required],
confirmPassword: ['', [Validators.required]],
},
{ validators: passwordMatchingValidator }
);
}
please note that notMatched is a custom validator I wrote myself.
password matcher validator:
export const passwordMatchingValidator: ValidatorFn = (
control: AbstractControl
): ValidationErrors | null => {
const password = control.get('newPassword');
const confirmPassword = control.get('confirmPassword');
return password?.value === confirmPassword?.value
? null
: { notMatched: true };
};