Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Email Validator

I'm having trouble with my simple email validator. My .ts page that controls my html has this code:

import {EmailValidator} from  '../../validators/email';
@Component({
  templateUrl: 'build/pages/auth-signup/auth-signup.html',
})

export class AuthSignupPage {
  constructor(private formBuilder: FormBuilder) {
     this.slideOneForm = new FormGroup({
          firstName: new FormControl('', [
              Validators.maxLength(30), 
              Validators.pattern('[a-zA-Z ]*'),
              Validators.required
              ]),
          lastName: new FormControl('', [
              Validators.maxLength(30), 
              Validators.pattern('[a-zA-Z ]*'), 
              Validators.required]),
          email: new FormControl('', [
              Validators.maxLength(30), 
              EmailValidator.isValidMailFormat, 
              Validators.required]),
          password: new FormControl('', [
              Validators.maxLength(30), 
              Validators.required]),
          confirmPassword: new FormControl('', [
              Validators.maxLength(30), 
              Validators.required])
      });
  }
}

My HTML code is:

  <ion-item>
    <ion-label floating>Email (this will be your login/username)</ion-label>
    <ion-input #email (change)="elementChanged(email)" formControlName="email" type="email" [class.invalid]="!slideOneForm.controls.email.valid && (emailChanged || submitAttempt)"></ion-input>
  </ion-item>

And finally, my email.ts that holds my validator looks like this:

import {Control} from '@angular/common';


export class EmailValidator {

   static isValidMailFormat(control: Control){
        var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;

        if (control.value != "" && (control.value.length <= 5 || !EMAIL_REGEXP.test(control.value))) {
            return { "Please provide a valid email": true };
        }

        return null;
    }

}

I keep having errors when referencing this validator in my main .ts file. For example, I get this error when hovering over "EmailValidator.isValidMailFormat"

[ts] 
Argument of type '(ValidatorFn | ((control: Control) => { "Please provide a valid email": boolean; }))[]' is not assignable to parameter of type 'ValidatorFn | ValidatorFn[]'.
  Type '(ValidatorFn | ((control: Control) => { "Please provide a valid email": boolean; }))[]' is not assignable to type 'ValidatorFn[]'.
    Type 'ValidatorFn | ((control: Control) => { "Please provide a valid email": boolean; })' is not assignable to type 'ValidatorFn'.
      Type '(control: Control) => { "Please provide a valid email": boolean; }' is not assignable to type 'ValidatorFn'.
        Types of parameters 'control' and 'c' are incompatible.
          Type 'AbstractControl' is not assignable to type 'Control'.
            Property 'updateValue' is missing in type 'AbstractControl'.
import EmailValidator

What am I doing wrong?

like image 296
Will Avatar asked Aug 30 '16 22:08

Will


People also ask

What is ValidatorFn in Angular?

ValidatorFnlinkA function that receives a control and synchronously returns a map of validation errors if present, otherwise null. interface ValidatorFn { (control: AbstractControl<any, any>): ValidationErrors | null }

How do I find regular expressions in an email?

[a-zA-Z0-9+_. -] matches one character from the English alphabet (both cases), digits, “+”, “_”, “.” and, “-” before the @ symbol. + indicates the repetition of the above-mentioned set of characters one or more times.

What are async validators?

The async validator's validate method returns a Promise that resolves if validation passes and value is updated or rejects with an Error if validation does not pass and value is not updated. The async validator also has a hint field that returns a Promise that when resolved will return a hint.

How do I remove required validator?

Either first use “clearValidators()” to remove all validators and then use “setValidators()” to set needed validation. Or directly use “setValidators()” with the needed validators only (without the validator you don't want to have).


2 Answers

Even better, now, Angular 4 has email validator built-in https://github.com/angular/angular/blob/master/CHANGELOG.md#features-6 https://github.com/angular/angular/pull/13709

Just add email to the tag. For example,

  <form #f="ngForm">
    <input type="email" ngModel name="email" required email>
    <button [disabled]="!f.valid">Submit</button>
    <p>Form State: {{f.valid?'VALID':'INVALID'}}</p>
  </form>
like image 141
so-random-dude Avatar answered Oct 18 '22 21:10

so-random-dude


This was solved by changing the imported class from Control to FormControl in the first line of my validator.ts:

import {FormControl} from '@angular/forms';


export class EmailValidator {

   static isValidMailFormat(control: FormControl){
        let EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;

        if (control.value != "" && (control.value.length <= 5 || !EMAIL_REGEXP.test(control.value))) {
            return { "Please provide a valid email": true };
        }

        return null;
    }

}
like image 36
Will Avatar answered Oct 18 '22 21:10

Will