gpt4 book ai didi

validation - Angular2 模板驱动的异步验证器

转载 作者:太空狗 更新时间:2023-10-29 16:58:35 26 4
gpt4 key购买 nike

我在以模板驱动形式定义异步验证器时遇到问题。

目前我有这个输入:

<input type="text" ngControl="email"  [(ngModel)]="model.applicant.contact.email" #email="ngForm" required asyncEmailValidator>

带有指向此类的验证器选择器 asyncEmailValidator:

import {provide} from "angular2/core";
import {Directive} from "angular2/core";
import {NG_VALIDATORS} from "angular2/common";
import {Validator} from "angular2/common";
import {Control} from "angular2/common";
import {AccountService} from "../services/account.service";

@Directive({
selector: '[asyncEmailValidator]',
providers: [provide(NG_VALIDATORS, {useExisting: EmailValidator, multi: true}), AccountService]
})

export class EmailValidator implements Validator {
//https://angular.io/docs/ts/latest/api/common/Validator-interface.html


constructor(private accountService:AccountService) {
}

validate(c:Control):{[key: string]: any} {
let EMAIL_REGEXP = /^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i;

if (!EMAIL_REGEXP.test(c.value)) {
return {validateEmail: {valid: false}};
}

return null;

/*return new Promise(resolve =>
this.accountService.getUserNames(c.value).subscribe(res => {
if (res == true) {
resolve(null);
}
else {
resolve({validateEmailTaken: {valid: false}});
}
}));*/
}

电子邮件正则表达式部分按预期工作,如果正则表达式匹配,则表单验证成功。但在那之后我想检查电子邮件是否尚未使用,所以我为我的帐户服务创建了 promise 。但这根本不起作用,表格一直处于失败状态。

我已经阅读了有关模型驱动表单和使用 FormBuilder 的信息,如下所示:

constructor(builder: FormBuilder) {
this.email = new Control('',
Validators.compose([Validators.required, CustomValidators.emailFormat]), CustomValidators.duplicated
);
}

它在 Control() 的第三个参数中定义了异步验证器,但这不是我的情况,因为我使用的是不同的方法。

所以,我的问题是:是否可以使用模板驱动的表单创建异步验证器?

最佳答案

您可以尝试使用 NG_ASYNC_VALIDATORS 键而不是 NG_VALIDATORS 注册异步验证器的提供者(仅适用于同步验证器):

@Directive({
selector: '[asyncEmailValidator]',
providers: [
provide(NG_ASYNC_VALIDATORS, { // <------------
useExisting: EmailValidator, multi: true
}),
AccountService
]
})
export class EmailValidator implements Validator {
constructor(private accountService:AccountService) {
}

validate(c:Control) {
return new Promise(resolve =>
this.accountService.getUserNames(c.value).subscribe(res => {
if (res == true) {
resolve(null);
}
else {
resolve({validateEmailTaken: {valid: false}});
}
}));
}
}

请参阅 angular.io 网站上的此文档:

关于validation - Angular2 模板驱动的异步验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36235446/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com