I'm trying to create a custom async validator for my registration form where it checks if an email is a valid email or not using third party API. this is ref link of the API website -
https://www.zerobounce.net/email-validation-api.html
I am trying to implement it using RxJs debounceTime, distinctUntilChanged. In the form control I have two more validations required and pattern. But I am always getting this error - Error: Expected validator to return Promise or Observable.
I have searched several examples but nothing worked. Thank you 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))
})