i`m having problem trying to implement async validator. This is my try:
export class EmailValidator {
static createValidator(): AsyncValidatorFn {
return (control: AbstractControl): Observable<ValidationErrors | null> => {
return of({}).pipe(
delay(1000),
tap(() => {
const isMatch = /[A-Za-z0-9]{6,}@gmail.com/.test(control.value);
return isMatch ? null : { invalidEmail: true }
})
)
};
}
}
This is basic creation of the form:
this.loginForm = this.fb.group({
email: [
'',
[
Validators.required,
],
EmailValidator.createValidator()
],
password: [
'',
[
Validators.required,
Validators.minLength(8)
]
]
});
And this is my html:
<div class="container">
<ul>
<li class="active"><a routerLink="/login">Login</a></li>
<li><a routerLink="/auth/register">Register</a></li>
</ul>
<form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
<input formControlName="email" type="email" placeholder="email">
<div *ngIf="(loginForm.get('email')?.touched || loginForm.get('email')?.dirty) && loginForm.get('email')?.errors?.required">
Email is required!
</div>
<div *ngIf="loginForm.get('email')?.errors?.invalidEmail">
Email is invalid!
</div>
<input formControlName="password" type="password" placeholder="password">
<input type="submit" value="Login">
</form>
</div>
When i try to debug inside validator it returns null if match and error object if no match. For some reason error div is not rendering.
emailAsyncValidatorDirectiveto your template, but the implementation code is missing. Can you please provide that as well in your initial question.