A J Qarshi
A J Qarshi

Reputation: 2992

Angular 2- Error: Type 'AbstractControl' is not assignable to type 'AbstractControl'

I am using the angular rc4 release to write an application where I have to impose few validation rules to form components like required, minlength along with some custom validator emailValidator.

When I pass one built in and one custom validator to the Validators.compose function, IDEs (both Webstorm & VS Code) display me compile time error messages like the one shown below:

enter image description here

However, you can see that in the above screenshot if both validators are built in, there is no error message.

The definition of my custom validator is given below:

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 };
    }
}

Upvotes: 5

Views: 18554

Answers (3)

Andre Lombaard
Andre Lombaard

Reputation: 7105

I had a similar problem. In my case, I was calling a custom EmailValidator class included from a shared Angular 7 library I created. Because of

"@angular/forms": "~7.2.2"

in my package.json file two different minor versions of @angular/forms got installed for my library and the application including it, resulting in different TypeScript definition files. The solution was to

  1. Delete node_modules folder for both projects
  2. Delete package-lock.json for both projects
  3. Do a npm install for both projects
  4. Reinstall the library

Upvotes: 1

A J Qarshi
A J Qarshi

Reputation: 2992

I solved the problem by replacing the type of control parameter from AbstractControl to Control as shown below:

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 class extends from AbstractControl. I still don't understand why I get this error message when I use FormControl or AbstractControl.

Upvotes: 1

Yoanribeiro
Yoanribeiro

Reputation: 145

This is rather strange, have you already tried with the FormControl?

Like this?

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
    }
}

I do use Validator.compose in my components and it works just fine.

Upvotes: 0

Related Questions