I am currently working on developing a custom async validator for my registration form. The purpose of this validator is to verify if an email is valid or not by utilizing a third-party API. Here is the reference link to the API website -
My approach involves implementing this validator using RxJs debounceTime and distinctUntilChanged. In addition to checking email validity, there are two other mandatory validations required in the form control. However, I keep encountering the following error - Error: Expected validator to return Promise or Observable.
I have explored various examples but none seem to address this issue effectively. Thank you for any assistance provided in advance.
Validator -
export class UniqueEmailValidator{
static createValidator(_ajaxService : AjaxService){
return (control : AbstractControl) =>{
const apiKey = environment.emailValidatationKey;
const baseUrl = 'https://api.zerobounce.net/v2/validate?';
if(control.valid){
return control
.valueChanges
.pipe(
debounceTime(800),
distinctUntilChanged(),
switchMap((email : string) => _ajaxService.apiCall('', `${baseUrl}api_key=${apiKey}&email=${email}&ip_address=''`, 'GET', true)),
map(res => res.json()),
map((validationStatus : any) => {
if (
validationStatus.status == "valid" &&
validationStatus.mx_found == "true"
) {
return null
} else {
return { isEmailInvalid : true }
}
})
)
}
}
}
}
Register Component -
this.registration = this._formBuilder.group({
firstName: new FormControl('', [
Validators.required,
Validators.pattern('^[a-z A-Z]+$')
]),
lastName: new FormControl('', [
Validators.required,
Validators.pattern('^[a-z A-Z]+$')
]),
email: new FormControl('', [
Validators.required,
Validators.pattern('[A-Za-z0-9._%-]+@[A-Za-z0-9._%-]+\\.[a-z]{2,3}')
],UniqueEmailValidator.createValidator(this._ajaxService))
})