Angular Email Validation in Reactive Form with Example

Angular Email Validation in Reactive Form with Example

In this article, We’ll see an example of Angular email validation in Reactive Form using angular built-in validators called EmailValidator and PatternValidator. We’ll see the example for reactive forms . If you’re using template driven form then read this article. Angular Email Validation in Template Driven Form Example

Email validation is one of the necessary things that every application must check for. Because it helps you to protect against bounces and to avoid spam traps. It doesn’t waste your time and money emailing bad leads. Invalid emails will never convert. Validating emails ensures that you are contacting interested parties.

Fortunately Angular offers built-in directives to validate an email.

We can do Email Validation in Angular using one of the following directives based on our needs.

  1. EmailValidator : It’s a built-in directive in angular that adds the email validator to controls marked with the email attribute.
  2. PatternValidator : This directive allows us to provide our custom regular expression (regex) to validate an email. This validator will be helpful if we want to only allow company’s email address and etc.
  3. Custom Validator: You can create your custom validator for validating an email if none of the above works for your case. Read Custom Validator in Angular to know more about it.

Now we’ll see an example of email validation in angular.

1. Angular Email Validation using EmailValidator

Now we’ll see an example of angular email validation in Reactive Forms.

Angular Email Validation in Reactive Forms

For the reactive forms, we’ll need to include ReactiveFormsModule in app.module.ts as following:

import { NgModule } from "@angular/core"; import { BrowserModule } from "@angular/platform-browser"; import { ReactiveFormsModule, FormsModule } from "@angular/forms"; import { AppComponent } from "./app.component"; import { HelloComponent } from "./hello.component"; import { ReactiveFormEmailValidationComponent } from "./components/reactive-form-email-validation/reactive-form-email-validation.component"; import { TemplateDrivenFormEmailValidationComponent } from "./components/template-driven-form-email-validation/template-driven-form-email-validation.component"; @NgModule({ imports: [BrowserModule, ReactiveFormsModule, FormsModule], declarations: [ AppComponent, HelloComponent, ReactiveFormEmailValidationComponent, TemplateDrivenFormEmailValidationComponent ], bootstrap: [AppComponent] }) export class AppModule {}

We can validation an email in angular reactive form using following 2 ways:

  1. Using EmailValidator
  2. Using email attribute

1. Using Email Validator

Step:1 creating reactive form and assigning email validator

We can define Email validator to the FormControl by using Validators.email as following:

import { Component, OnInit } from "@angular/core"; import { FormControl, FormGroup, FormBuilder, Validators } from "@angular/forms"; @Component({ selector: "app-reactive-form-email-validation", templateUrl: "./reactive-form-email-validation.component.html", styleUrls: ["./reactive-form-email-validation.component.css"] }) export class ReactiveFormEmailValidationComponent implements OnInit { userRegistrationForm: FormGroup; constructor(private fb: FormBuilder) {} ngOnInit() { this.userRegistrationForm = this.fb.group({ name: ["", Validators.required], email: ["", Validators.email] }); } }

In the above code, I’ve created reactive forms with 2 controls. The first control is name with required validator and the second is email with email validator. You can apply email validator by adding Validatord.email to form control.

Step:2 Displaying error message and making form control invalid in template

<form [formgroup]="userRegistrationForm"> <div class="form-group"> <label>Name:</label> <input type="text" [class.is-invalid]="userRegistrationForm.get('name').invalid && userRegistrationForm.get('name').touched" class="form-control" formcontrolname="name"> <div *ngif="(userRegistrationForm.get('name').invalid && userRegistrationForm.get('name').touched) || userRegistrationForm.get('name').dirty"> <small *ngif="userRegistrationForm.get('name').errors?.required" class="text-danger">Name is required</small> </div> </div> <div class="form-group"> <label>Email:</label> <input type="email" [class.is-invalid]="userRegistrationForm.get('email').invalid && userRegistrationForm.get('email').touched" class="form-control" formcontrolname="email"> <div *ngif="(userRegistrationForm.get('email').invalid && userRegistrationForm.get('email').touched) || userRegistrationForm.get('email').dirty"> <small class="text-danger" *ngif="userRegistrationForm.get('email').errors?.required">Email address is required</small> <small class="text-danger" *ngif="userRegistrationForm.get('email').errors?.email">Email address is invalid</small> </div> </div> </form>

Here as you can see in the above code, I’ve used bootstrap 4 classes because I’m using bootstrap to style the form.

We’ve set [class.is-invalid] with some condition, so it’ll set the red border color to input if it’s invalid. It’s a default bootstrap style and we’ve also displayed error message below the input.

We’ve use the following code to show the error message if email is invalid:

<small class="text-danger" *ngif="userRegistrationForm.get('email').errors?.email">Email address is invalid</small>

To display the error messages conditionally to users, we’ve used form’s errors object with the *ngIf directive. We’ll check if the errors object exists and then access the email property.

You can dynamically set the email validator at runtime to formcontrol by using the following code:

setEmailValidator(){ this.userRegistrationForm.get('email').setValidators(Validators.email); }

Output

Angular Reactive Form Email Validation Example

2. Using email attribute

We can also use email attribute to validate an email in angular.

<input type="email" [class.is-invalid]="userRegistrationForm.get('email').invalid && userRegistrationForm.get('email').touched" class="form-control" formcontrolname="email" email="">

Here we’ve added email attribute in the above code.

To make it dynamic we could use angular property binding for that attribute as following:

<input type="email" [class.is-invalid]="userRegistrationForm.get('email').invalid && userRegistrationForm.get('email').touched" class="form-control" formcontrolname="email" [email]="emailValidation">

and we will need to declare the emailValidation variable in component file.

so our component file will look as follows:

import { Component, OnInit } from "@angular/core"; import { FormControl, FormGroup, FormBuilder, Validators } from "@angular/forms"; @Component({ selector: "app-reactive-form-email-validation", templateUrl: "./reactive-form-email-validation.component.html", styleUrls: ["./reactive-form-email-validation.component.css"] }) export class ReactiveFormEmailValidationComponent implements OnInit { userRegistrationForm: FormGroup; emailValidation: boolean = true; constructor(private fb: FormBuilder) {} ngOnInit() { this.userRegistrationForm = this.fb.group({ name: ["", Validators.required], email: [""] }); } }

Here in the above code, you might have noticed, we’ve removed Validators.email because we’re using email attribute in this example and we’ve also added new variable called emailValidation.

Our template file will look like:

<form [formgroup]="userRegistrationForm"> <div class="form-group"> <label>Name:</label> <input type="text" [class.is-invalid]="userRegistrationForm.get('name').invalid && userRegistrationForm.get('name').touched" class="form-control" formcontrolname="name"> <div *ngif="(userRegistrationForm.get('name').invalid && userRegistrationForm.get('name').touched) || userRegistrationForm.get('name').dirty"> <small *ngif="userRegistrationForm.get('name').errors?.required" class="text-danger">Name is required</small> </div> </div> <div class="form-group"> <label>Email:</label> <input type="email" [class.is-invalid]="userRegistrationForm.get('email').invalid && userRegistrationForm.get('email').touched" class="form-control" formcontrolname="email" [email]="emailValidation"> <div *ngif="(userRegistrationForm.get('email').invalid && userRegistrationForm.get('email').touched) || userRegistrationForm.get('email').dirty"> <small class="text-danger" *ngif="userRegistrationForm.get('email').errors?.required">Email address is required</small> <small class="text-danger" *ngif="userRegistrationForm.get('email').errors?.email">Email address is invalid</small> </div> </div> </form>

Output

Angular Reactive form email validation using email attribute

2. Angular Email Validation using PatternValidator

We can also validate an email using Pattern Validator directive. We’ll need to pass regex to Validator.pattern(). If the input won’t match regex then it’ll throw an error otherwise it’ll pass.

Now we’ll see how can we use PatternValidator directive in angular reactive forms.

Step:1 creating reactive form and assigning email validator

In reactive forms, we can create reactive forms and pass regex to PatternValidator as following:

this.userRegistrationForm = this.fb.group({ name: ["", Validators.required], email: ["",Validators.pattern("^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$")] });

Here in the above code, we’ve passed regex to Validators.pattern.

Step:2 Displaying error message and making form control invalid in template

and then we can show red border in input if input is invalid as following:

<input type="email" [class.is-invalid]="userRegistrationForm.get('email').invalid && userRegistrationForm.get('email').touched" class="form-control" formcontrolname="email">

Here as you can see in the above code, I’ve used bootstrap 4 classes because I’m using bootstrap to style the form.

We’ve set [class.is-invalid] with some condition, so it’ll set the red border colour to input if it’s invalid. It’s a default bootstrap style and we’ve also displayed error message below the input.

We’ve use the following code to show the error message if email is invalid:

<small class="text-danger" *ngif="userRegistrationForm.get('email').errors?.pattern">Email address is invalid</small>

To display the error messages conditionally to users, we’ve used form’s errors object with the *ngIf directive. We’ll check if the errors object exists and then access the pattern property.

You can dynamically set the pattern validator at runtime to formcontrol by using the following code:

setPatternValidator(){ this.userRegistrationForm.get('email').setValidators(Validators.pattern("^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$")); }

Full Code

reactive-forms-email-pattern-validation.component.ts

import { Component, OnInit } from '@angular/core'; import { FormControl, FormGroup, FormBuilder, Validators } from "@angular/forms"; @Component({ selector: 'app-reactive-forms-email-patter-validation', templateUrl: './reactive-forms-email-patter-validation.component.html', styleUrls: ['./reactive-forms-email-patter-validation.component.css'] }) export class ReactiveFormsEmailPatterValidationComponent implements OnInit { userRegistrationForm: FormGroup; constructor(private fb: FormBuilder) {} ngOnInit() { this.userRegistrationForm = this.fb.group({ name: ["", Validators.required], email: ["",Validators.pattern("^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$")] }); } }

reactive-forms-email-pattern-validation.component.html

<form [formgroup]="userRegistrationForm"> <div class="form-group"> <label>Name:</label> <input type="text" [class.is-invalid]="userRegistrationForm.get('name').invalid && userRegistrationForm.get('name').touched" class="form-control" formcontrolname="name"> <div *ngif="(userRegistrationForm.get('name').invalid && userRegistrationForm.get('name').touched) || userRegistrationForm.get('name').dirty"> <small *ngif="userRegistrationForm.get('name').errors?.required" class="text-danger">Name is required</small> </div> </div> <div class="form-group"> <label>Email:</label> <input type="email" [class.is-invalid]="userRegistrationForm.get('email').invalid && userRegistrationForm.get('email').touched" class="form-control" formcontrolname="email"> <div *ngif="(userRegistrationForm.get('email').invalid && userRegistrationForm.get('email').touched) || userRegistrationForm.get('email').dirty"> <small class="text-danger" *ngif="userRegistrationForm.get('email').errors?.required">Email address is required</small> <small class="text-danger" *ngif="userRegistrationForm.get('email').errors?.pattern">Email address is invalid</small> </div> </div> </form>

Output

Angular Email Validation using PatternValidator

That’s all for angular email validation in angular reactive form.

Also Read: