I created a unique validator to verify if an email already exists in the database before saving a new user, however, it appears that the validator is not functioning properly.
Here is my template:
<form class="forms-sample" #f="ngForm" (ngSubmit)="onSaveUser(f.value)">
<input type="email" class="form-control" id="email" ngModel name="email" required pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$" #email="ngModel" placeholder="Email" emailValidator>
<div *ngIf="email?.errors.emailValidator">This email has been taken, please use another one.</div>
.......................................................
<button class="btn btn-md-12 btn-outline-primary btn-fw btn-icon-text clickable" [disabled]="f.invalid || userFile==null" type="submit">
</form>
This is my custom validator:
import { NG_VALIDATORS, FormControl, ValidatorFn, Validator } from '@angular/forms';
import { Directive } from '@angular/core';
import {UsersService} from '../../services/users.service';
@Directive({
selector: '[emailValidator][ngModel]',
providers: [
{
provide: NG_VALIDATORS,
useExisting: EmailValidator,
multi: true
}
]
})
export class EmailValidator implements Validator {
validator: ValidatorFn;
constructor(public usersService:UsersService) {
this.validator = this.emailValidator("");
}
validate(c: FormControl) {
return this.validator(c);
}
emailValidator(email:string): ValidatorFn {
return (c: FormControl) => {
this.usersService.checkEmailTaken(email)
.subscribe((res)=>{
let isValid = res;
if (isValid==null) {
return true;
}
});
return {
emailValidator: {
valid: false
}
};
}
}
}
My service returns the user data if it exists or null if it does not:
checkEmailTaken(email: string) {
if(this.jwtToken==null) this.authenticationService.loadToken();
return this.http.get(this.host+"/checkEmailTaken?email="+email
, {headers:new HttpHeaders({'Authorization':this.jwtToken})}
);
}
The service functions properly, but I am unable to determine why my custom validation is not working as expected. Any insights?