I am currently working on creating a custom validator for a template-driven form. The validator I have created (shown below) works perfectly for field-level validation, but I am facing an issue where the validation state for the entire form is not updating. This means that even when all the controls are valid, the form tag still displays class="ng-invalid".
Interestingly, when I remove the phoneValidator from the control in my template, everything functions as expected.
I suspect that the problem might be related to the registerOnValidatorChange method defined in the interface. Although I haven't implemented this method in my custom validator, I am unsure of how to utilize it effectively:
export interface Validator {
validate(c: AbstractControl): ValidationErrors | null;
registerOnValidatorChange?(fn: () => void): void;
}
Any insights or suggestions on this issue would be greatly appreciated. Thank you!
file: phonevalidator.directive.ts:
import { Directive, forwardRef } from '@angular/core';
import { NG_VALIDATORS, AbstractControl, ValidationErrors, Validator, FormControl } from '@angular/forms';
@Directive({
selector: '[validPhoneNumber]',
providers: [
{ provide: NG_VALIDATORS, useExisting: PhoneValidatorDirective, multi: true }
]
})
export class PhoneValidatorDirective implements Validator {
validate(control: FormControl): ValidationErrors | null {
return PhoneValidatorDirective.validatePhone(control);
}
static validatePhone(control: FormControl): ValidationErrors | null {
var regEx = new RegExp(/^[1-9]\d{2}-\d{3}-\d{4}/);
console.log("Phone validator: validating phone number.")
var controlValue: string = control.value;
console.log(regEx.exec(controlValue));
if (!(regEx.exec(controlValue))) {
// Return error if phone number is not valid
console.log('returning false');
return { phoneNumber: false };
} else {
// If no error, return null
console.log('returning true');
return { phoneNumber: true };
}
}
}