8

I'm using a reactive form to get user input. Not satisfied with the EmailValidator I'm using a pattern.

emailRegEx = '^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$';
this.email = new FormControl('', [Validators.required, Validators.pattern(emailRegEx)]);

And the HTML:

<input type="email" formControlName="email" [ngClass]="contactForm.get('email').errors && (contactForm.get('email').dirty || isButtonClicked) ? 'contact-input input-error' : 'contact-input'">

But here's the thing, for some reason the regex is accepting 4 chars after the @, without a period. name@d --> error
name@doma --> no error
name@domain. --> error
name@domain.com --> no error

I checked this regex in multiple online regex testers, and they all only accept the last example above, none of them accept the second one.

EDIT:
The regular expression is fine and works well, the problem is that somehow the pattern validator isn't parsing the regex correctly, or something.

AvailableName
  • 666
  • 4
  • 13
  • 24
  • 2
    Possible duplicate of [How to validate an email address using a regular expression?](https://stackoverflow.com/questions/201323/how-to-validate-an-email-address-using-a-regular-expression) – msanford Mar 08 '18 at 14:07
  • 2
    This is not a duplicate, I made a stackblitz reproducing : https://stackblitz.com/edit/stackoverflow-49175054 The regex looks good, tried in the notepad++ search and behave well. – ibenjelloun Mar 08 '18 at 14:22
  • I'm still not entirely convinced that the problem of validating emails with regex hasn't been redone a hundred times on SO, but I retracted by close vote anyway. :) – msanford Mar 08 '18 at 15:34

4 Answers4

17

The pattern is not correct as a string. In deed you are inside a string so to escape '.' you need to use double backslash like:

emailRegEx = '^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$'

Or if you want to avoid doing so i suggest to use:

emailRegEx = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/

Edit: Keep in mind that this is a simple pattern that exclude a lot of valid email address (see RFC 5322 (sections 3.2.3 and 3.4.1) and RFC 5321). For example the angular build in email validator use the following pattern

/^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(\.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/
Community
  • 1
  • 1
JEY
  • 6,973
  • 1
  • 36
  • 51
1

You can use CustomValidator package that offers too much types of validation :https://www.npmjs.com/package/ng2-validation

import it like that :

import { CustomValidators } from 'ng2-validation';

and use it in your form control :

this.email = new FormControl('', [Validators.required, CustomValidators.email]);

Regards,

Mohamed Ali RACHID
  • 3,245
  • 11
  • 22
  • Why is this better than angular's build-in `EmailValidator`, the HTML5 `input type="email"` validator, or the above regex? – msanford Mar 08 '18 at 14:12
  • 2
    why downvote ? i did not said that is better , i suggested a solution for his problem my friend :) – Mohamed Ali RACHID Mar 08 '18 at 14:25
  • 1
    It's a simple library suggestion, which should be a comment. The code is boilerplate and doesn't add any value as an answer (OP knows how to load and instantiate a validator) [so the answer boils down to the link](https://meta.stackoverflow.com/questions/265552/when-to-flag-an-answer-as-not-an-answer). What _would add value_ would be to explain, in-line, why this library fixes OP's problem – msanford Mar 08 '18 at 15:36
1

I use this:

/^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/ 
vladernn
  • 835
  • 1
  • 6
  • 7
-1
import {Component} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';

@Component({
    templateUrl: './forgot-password.component.html',
    styleUrls: ['./forgot-password.component.scss']
})
export class ForgotPasswordComponent {

    psResetForm: FormGroup;

    constructor(private fb: FormBuilder) {
        this.psResetForm = fb.group({
            'email': [null, Validators.compose([Validators.required, Validators.email])]
        });
    }

    makeRequestToResetLink(formData, valid: boolean) {
        if (valid) {
            alert(formData.email);
        }
    }

}

Your Template should look like this

<form [formGroup]="psResetForm" (ngSubmit)="makeRequestToResetLink(psResetForm.value,psResetForm.valid)">
    <input type="email" formControlName="email"/>
    <button type="submit">
        submit
    </button>
</form>
Imal Hasaranga Perera
  • 9,683
  • 3
  • 51
  • 41