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.
To get a valid email id we use a regular expression /^[a-zA-Z0-9.! #$%&'*+/=? ^_`{|}~-]+@[a-zA-Z0-9-]+(?:\. [a-zA-Z0-9-]+)*$/.
You should not use regular expressions to 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.
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>
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) ]], });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With