我正在尝试为我的注册表单创建一个自定义异步验证器,用于检查电子邮件是否为有效电子邮件或不使用第三方 API。这是 API 网站的参考链接 -
https://www.zerobounce.net/email-validation-api.html
我正在尝试使用 RxJs debounceTime, distinctUntilChanged 来实现它。在表单控件中,我需要另外两个验证和模式。但我总是收到此错误 -错误:预期验证器返回 Promise 或 Observable。
我搜索了几个例子,但没有任何效果。先感谢您。
验证器 -
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 }
}
})
)
}
}
}
}
注册组件 -
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))
})