Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic email validator

I want to create a form where the user will enter his email. I'd like to validate email format client-side.

Is there any generic email validator in Angular 2?

NB: Something similar to AngularJS validator.

like image 943
Julien Alary Avatar asked Dec 03 '15 17:12

Julien Alary


People also ask

What is regex validation in email?

To get a valid email id we use a regular expression /^[a-zA-Z0-9.! #$%&'*+/=? ^_`{|}~-]+@[a-zA-Z0-9-]+(?:\. [a-zA-Z0-9-]+)*$/.

Can we use regex for email validation in validation rules?

You should not use regular expressions to validate email addresses.

Should you validate email addresses?

Why do you need to verify email addresses? The thing is that many hard bounces impair your sender's reputation. The poor reputation, in turn, drops your deliverability. If you regularly send emails to invalid addresses, your email campaigns will end up in the spam folder.


2 Answers

You can do only using html:

<md-input-container class="md-icon-float md-block" flex-gt-sm>     <label>Email</label>         <input md-input             id="contact-email"             type="text"             ngControl="email"             #email="ngForm"             [(ngModel)]="contact.email"             required             pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,6})+$">      <div class="md-errors-spacer" [hidden]="email.valid || email.untouched">         <div class="md-char-counter" *ngIf="email.errors && email.errors.required">             Email is required         </div>         <div class="md-char-counter" *ngIf="email.errors && email.errors.pattern">             Email is invalid         </div>     </div> </md-input-container> 
like image 56
Mush Avatar answered Sep 22 '22 08:09

Mush


For angular 4 and above:

According to This you can use "email validator".

Example:

If you use template-driven forms:

<input type="email" name="email" email> <input type="email" name="email" email="true"> <input type="email" name="email" [email]="true"> 

If you use model-driven forms(aka ReactiveFormsModule) use Validators.email:

this.myForm = this.fb.group({     firstName: ['', [<any>Validators.required]],     email: ['', [<any>Validators.required, <any>Validators.email]], }); 

Old answer: You can use angular 2 FormGroup,

By using validators.pattern and regex like this:

 let emailRegex = '^[a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,15})$';  this.myForm = this.fb.group({         firstName: ['', [<any>Validators.required]],         email: ['', [<any>Validators.required,  <any>Validators.pattern(emailRegex) ]],  }); 
like image 42
Asaf Hananel Avatar answered Sep 24 '22 08:09

Asaf Hananel