I have encountered an issue while trying to implement a custom validator in a template-driven form within my Angular project. It seems that the ngModel is not recognizing the custom validator. Can you help me identify what might be causing this problem?
The custom validator code is as follows:
import { Directive } from '@angular/core';
import { AbstractControl, FormControl, NG_VALIDATORS, Validator, ValidatorFn } from '@angular/forms';
function usernameExistsFactory(): ValidatorFn {
return (c: AbstractControl) => {
let isValid = c.value === 'Juri';
if (isValid) {
return null;
} else {
return {
usernameExists: true
};
}
};
}
@Directive({
selector: 'usernameExistsValidator',
providers: [
{ provide: NG_VALIDATORS, useExisting: usernameExistsValidator, multi: true }
]
})
export class usernameExistsValidator implements Validator {
validator: ValidatorFn;
constructor() {
this.validator = usernameExistsFactory();
}
validate(c: FormControl) {
return this.validator(c);
}
}
The input element where the custom validator should be applied is as shown below:
<input (change)="log(name)" required usernameExistsValidator ngModel minlength="3" maxlength="32" name="name" #name="ngModel" type="text" class="form-control" id="name">
Upon inspection, the ngModel does not seem to be registering the validation properly.