Generic email validator
Solution 1:
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>
Solution 2:
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) ]],
});