2016-08-15 153 views
0

我正在使用rc4角度发布来编写一个应用程序,其中我必须施加几个验证规则以形成像required,minlength一些组件验证程序emailValidatorAngular 2-错误:类型'AbstractControl'不可分配给'AbstractControl'类型

当我通过一个内置的,一个自定义验证到Validators.compose功能,集成开发环境(二者Webstorm & VS码)显示我编译如下所示的一个时间错误消息:

enter image description here

然而,你可以看到在上面的屏幕截图中,如果两个验证器都是内置的,那么就没有错误信息。

static emailValidator(control: AbstractControl): {[key: string]: boolean} { 
    if (control.value.match(/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/)) { 
     return null; 
    } else { 
     return {'invalidEmailAddress': true }; 
    } 
} 

回答

0

我通过从AbstractControl替换control参数的类型Control解决了这个问题,如下所示:

static emailValidator(control: Control): {[key: string]: boolean} { 
    if (control.value.match(/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/)) { 
     return null; 
    } else { 
     return {'invalidEmailAddress': true }; 
    } 
} 

Control类从AbstractControl延伸。我仍然不明白为什么当我使用FormControlAbstractControl时收到此错误消息。

0

这是很奇怪的,你已经与FormControl尝试:

我的自定义验证的定义如下?

是否这样?

static emailValidator(control : FormControl){ 
    // RFC 2822 compliant regex 
    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; 

    return EMAIL_REGEXP.test(control.value) ? null : { 
     invalidEmailAddress:true 
    } 
} 

我在我的组件中使用Validator.compose,它工作得很好。

+0

是的,我做到了。事实上,我首先使用从'AbstractControl'继承的'FormControl'。 –

+0

@AJQarshi确切地说,这就是为什么这个错误是奇怪的,我通常首先声明FormControl ' this.emailControl = new FormControl('',Validators.compose([Validator.required,ValidatorService.emailValidator]),ValidatorService.checkEmai this._httpService)); ' 然后我将它分配给FormGroup输入对象的一个​​键 – Yoanribeiro

相关问题