I have created a validator directive that makes an HTTP request that checks if an email already exists.
I can see that the API call happening but in the template the validation is not working
Directive:
@Directive({
selector:
'[emailValidator][formControlName],[emailValidator][formControl],[emailValidator][ngModel]',
providers: [
{
provide: NG_ASYNC_VALIDATORS,
useExisting: forwardRef(() => EmailValidatorDirective),
multi: true
}
]
})
export class EmailValidatorDirective implements Validator {
constructor(private _http: HttpService) {}
validate(
c: AbstractControl
): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> {
return this.validateEmail(c.value);
}
private validateEmail(email: String): Observable<ValidationErrors | null> {
return this._http.post('user/validate-email', { email }).pipe(
debounceTime(500),
distinctUntilChanged(),
map((isUsed) => {
// null no error, object for error
return !isUsed
? null
: {
isTaken: 'Email exists already.'
};
})
);
}
}
Template:
<input
id="email"
type="email"
class="form-control"
formControlName="email"
emailValidator
placeholder="Enter E-mail Address"
/>
// always showing null
{{ formcontrol['email'].errors | json }}