40

I am new in learning Angular2, and I want to make a validation form that verifies emails after a RegEx pattern.

My code looks something like this but I don't have any idea if I am doing it right, or what I did wrong, can somebody please help me a bit?

1
  • you have to remove the regex delimiter / Commented Feb 21, 2017 at 11:59

11 Answers 11

62

Angular 4 has a built-in "email" validation tag that can be added within the input. E.g.:

<input type="email" id="contactemail" email>

This will be valid for a series of numbers and letters then an @ then another series of letters. It will not account for the dot after the @ -- for that you can use the "pattern" tag within the input and your standard regex.

Sign up to request clarification or add additional context in comments.

9 Comments

Only available since Angular4
When using it this way the input is implicitly required - even if not specifying "required". Bug or feature?
Resolved. With this <input type="text" class="form-control" #userEmail="ngModel" name="email" [(ngModel)]="email" pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$" [ngClass]="{invalid : userEmail.touched && !userEmail?.valid}" required email>
There is no requirement for an e-mail address to end with a .com or anything of the sort. user@localhost is valid
what should be the *ngIf condition for showing error message??
|
51

Try Something like that

<div class="alert-email">
        <label>Email</label>
            <input
                id="contactemail"
                type="text"                
                #contactemail="ngModel"
                [(ngModel)]="model.contactemail"
                required
                pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$">

        <div class="md-errors-spacer" [hidden]="contactemail.valid || contactemail.untouched">
            <div  *ngIf="contactemail.errors && contactemail.errors.required">
                Email is required
            </div>
            <div  *ngIf="contactemail.errors && contactemail.errors.pattern">
                Email is invalid
            </div>
        </div>
    </div>

4 Comments

there are new TLDs you should change accordingly
<label for="CompanyEmail" class="control-label">Company Email</label> <input id="CompanyEmail" type="text" [(ngModel)]="user.Email" class="form-control" pattern="[a-zA-Z0-9.-]{1,}@[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,}" required #CompanyEmail="ngModel" placeholder="Please enter Company Email address" /> <div *ngIf="CompanyEmail.invalid && (CompanyEmail.dirty || CompanyEmail.touched)" class="alert alert-danger"> <div *ngIf="CompanyEmail.errors.required"> Company Email is required. <div *ngIf="CompanyEmail.errors && CompanyEmail.errors.pattern"> Email is invalid
Worked for me using Angular5. Copied pattern as-is, copied "Email is invalid" div as-is.
This looks like yet another ad hoc regex which will accept invalid addresses and reject valid ones. Don't roll your own.
30

Angular 4 Email Validation :

  • Use email to your input
  • If you want .com for email use pattern pattern="[a-zA-Z0-9.-_]{1,}@[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,}

Final :

`<input type="email" [(ngModel)]="enterEmail" name="myEmail" #myEmail="ngModel" email pattern="[a-zA-Z0-9.-_]{1,}@[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,}" required>`

2 Comments

There is an error in [a-zA-Z0-9.**-**_]{1,}@[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,}. The minus char must be escaped. I prefer ^[a-zA-Z]{1}[a-zA-Z0-9.\-_]*@[a-zA-Z]{1}[a-zA-Z.-]*[a-zA-Z]{1}[.][a-zA-Z]{2,}$
Hint: any regex which contains {1} was written by someone who is only just beginning to learn about regular expressions.
6

You can use this pattern for your email inputs:

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

ref

This pattern accepts "sample@domain" also in addition of "[email protected]". Using this email pattern "sample@domain." is not acceptable and 1 letter domain tld is not allowed ("[email protected]" goes wrong).

Comments

4

For multiple email validation in a single field, you can do using the custom email validator.

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

export class EmailValidator {

public static isValid(email) {
    var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(String(email).toLowerCase());
}

static isMultiValid(control: FormControl): any {

  console.log(control.value);
  let tempEmail = control.value;
  let invalid = false;
  let regex =/[a-z0-9!#$%&'*+=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/g;

  if(tempEmail.indexOf(',') > -1){
    var emails = control.value.split(',');
      for (let email of emails) {
        console.log(email);
        let isValid = EmailValidator.isValid(email)
        if(!isValid){
          return{"email not valid":isValid}
        }
      }
      return null;
  }
  else{
    let email = control.value.split(',');
    if( email == "" || ! regex.test(email)){
        invalid = true;
        return {
            "email not valid": invalid
        };
    }
    console.log("valid");
    return null;

   }
  }
}

.

Comments

1

Try this:

^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$

1 Comment

Hello & Welcome to StackOverflow! While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. Please read the tour, and How do I write a good answer?
0

This pattern worked for me which will accept alphanumeric characters and '.' special character.

^[\\w]+(?:\\.[\\w])*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$

Comments

0

this pattern email working :

 <input  pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$">

Comments

0

Solution originally posted by the OP as part of the question:

<div class="alert-email">
    <label for="contactemail">EMAIL: </label>
    <input type="email" id="contactemail" name="contactemail"
           required ng-pattern="/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/"
           [(ngModel)]="model.contactemail" #contactemail="ngModel"
           placeholder="Your email" /><br><br>
    <div *ngIf="contactemail.errors && (contactemail.dirty || contactemail.touched)" class="alert-email alert-danger-email"><br>
      <div [hidden]="!contactname.errors.required">
        Email is required
      </div>
      <div [hidden]="!contactname.errors">
        Please input a valid email.
      </div>
    </div>
  </div>

1 Comment

Thank you for your interest in contributing to the Stack Overflow community. This question already has quite a few answers—including one that has been extensively validated by the community. Are you certain your approach hasn’t been given previously? If so, it would be useful to explain how your approach is different, under what circumstances your approach might be preferred, and/or why you think the previous answers aren’t sufficient. Can you kindly edit your answer to offer an explanation?
-2

This pattern worked for me :

 pattern="[a-zA-Z0-9.-]{1,}@[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{3,}"

Comments

-2

Try This One it will work:

^[a-zA-Z]+([.-]?[a-zA-Z0-9]+)*@([a-zA-Z]+([.-]?[a-zA-Z]))[.]{1}[a-zA-Z]{2,}$

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.