In my form-validators.ts file, I encountered an issue where the code snippet below always returned undefined
, causing the custom validation function matchPwdValidator()
to consistently return false
. By moving the logic to fetch confirmPwd inside the switch statement, I was able to retrieve the correct values. A condensed version of my code is provided below.
form-validators.ts
import { AbstractControl, ValidatorFn, Validators } from "@angular/forms";
export class FormValidators {
...
static matchPwdValidator(): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } | null => {
const password = control.get("password");
const confirmPwd = control.get("confirmPwd");
console.log('password:', password?.value);
console.log('confirmPwd:', confirmPwd?.value);
if (!password || !confirmPwd || password.value !== confirmPwd.value) {
return { PwdNotMatched: true };
}
return null;
};
}
}
form.component.ts
import { Component } from "@angular/core";
import { FormBuilder, FormGroup } from "@angular/forms";
import { FormValidators } from "../utilities/form-validators";
@Component({
selector: "app-form",
templateUrl: "./form.component.html",
styleUrls: ["./form.component.scss"],
})
export class FormComponent {
cpwdError: boolean = false;
sampleForm: FormGroup;
constructor(
private formBuilder: FormBuilder,
) {
this.sampleForm= this.formBuilder.group(
{
...
password: ["", FormValidators.passwordValidator()],
confirmPwd: ["", FormValidators.matchPwdValidator()],
},
);
...
this.sampleForm.get('confirmPwd')?.statusChanges .subscribe(() => {
this.updateErrorFlags('confirmPwd');
});
}
private updateErrorFlags(controlName: string): void {
const control = this.sampleForm.get(controlName);
if (control) {
switch (controlName) {
...
case 'confirmPwd':
this.cpwdError = control.hasError('PwdNotMatched') && control.dirty;
break;
}
}
}
}