{

Angular 13 Email validation example |How to check Email invalid or not in typescript?


Angular elements web components

You will learn how to do email validation in Angular and Typescript applications with input forms.

Email validation is one of the basic validation to avoid invalid emails.

In Angular, validations can be done using two approaches. -Reactive forms

We already have a pre-created angular application - angular-form-validations.

Angular Email Validation reactive forms

Email Validations are implemented in Reactive forms using in-built Angular directives. For Angular applications to use reactive forms,

In app.module.ts, first import the FormsModule and ReactiveFormsModule modules.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';


@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Let’s create a new component reactive-email-validation using the ng g component command.

A:\work\angular-form-validations>ng g component reactive-email-validation
CREATE src/app/reactive-email-validation/reactive-email-validation.component.html (40 bytes)
CREATE src/app/reactive-email-validation/reactive-email-validation.component.spec.ts (747 bytes)
CREATE src/app/reactive-email-validation/reactive-email-validation.component.ts (350 bytes)
CREATE src/app/reactive-email-validation/reactive-email-validation.component.scss (0 bytes)
UPDATE src/app/app.module.ts (973 bytes)

To begin, an HTML template component is constructed in Angular to display the input form with an email field.

  • Define the form element with FormGroup directive with emailForm binding
  • Inside form, define input element with formControlName name email
  • validation errors are bound and available with emailForm.controls[email]
  • Validation check added for input box is not empty(errors.required) and focus is in it(touched)
  • if bound errors contains required, display the error message ‘Email is required
  • if errors contain the pattern, display the error message ‘Invalid Email’.
<p>Angular Email Validation with Reactive form!</p>
<div>
    <h2>{{ heading | titlecase }}</h2>
    <form [formGroup]="emailForm">
        <input type="text" formControlName="email" />
        <div *ngIf="!emailForm.controls['email'].valid && emailForm.controls['email'].touched">
            <div *ngIf="emailForm.controls['email'].errors?['required']" style=" background-color: red">
                Email is required
            </div>
            <div *ngIf="emailForm.controls['email'].errors?['required']" style="background-color: red">
                Invalid Email
            </div>
        </div>
    </form>

    <button type="submit ">Submit</button>
</div>

Next, In the application controller component, define the logic for regex pattern validation.

  • Declared emailForm of type FormGroup which already has a binding to form element.
  • Defined the email regular expression pattern into variable
  • In the constructor, initialized emailForm with a new FormControl element ie email
  • these email form control will be bound with the input element in the HTML template
  • Validators.required added for not empty validation check
  • Validators.pattern added for email regular expression
  • These validations are checked with blur event `updateOn: blur’ property
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-reactive-email-validation',
  templateUrl: './reactive-email-validation.component.html',
  styleUrls: ['./reactive-email-validation.component.scss']
})
export class ReactiveEmailValidationComponent {
  heading = 'angular Email pattern validation with examples';
  emailForm: FormGroup;

  myusername: string = '';
  emailRegex =
    '^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$';

  constructor() {
    this.emailForm = new FormGroup({
      email: new FormControl('', {
        validators: [Validators.required, Validators.pattern(this.emailRegex)],
        updateOn: 'blur',
      }),
    });
  }
  submit() {
    console.log(this.emailForm.value);
  }
  get validator() {
    return true;
  }

}

Angular email template-driven form validation using html5

In modern browsers, the Easy approach is to do email pattern validation with inbuilt html5 language.

Another way to do email validation is to define the input type=email in the HTML element. However, this only supports html5 only and modern browsers.

Input is defined with following attributes

<input type="email" name="email" id="email" placeholder="abc@gmail.com" [(ngModel)]="email" [ngModelOptions]="{ updateOn: 'blur' }" #emailerror="ngModel" pattern="^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$ "        required />

type=email is an input textbox, that accepts email only pattern attribute value is a regular expression pattern for email values NgModel directive is to support two-way binding from view to controller and vice versa The ngModelOptions directive enables to change of the behavior of the ngModel value, this will be fired with the updateon:blur event.

Following is an complete code

<div>
<input type="email" name="email" id="email" placeholder="abc@gmail.com" [(ngModel)]="email" [ngModelOptions]="{ updateOn: 'blur' }" #emailerror="ngModel" pattern="^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$ "        required />
    <div *ngIf="emailerror.invalid && (emailerror.dirty || emailerror.touched)">
        <div *ngIf="emailerror.errors.required">
            <span style="background-color: red">Email is required </span>
        </div>
        <div *ngIf="emailerror.errors.pattern">
            <span style="background-color: red">Invalid EmailL </span>
        </div>
    </div>
</div>

In the component, just declare the input element’s name here with a default value.

import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  heading = 'angular html5 Email pattern validation  example';

  email: string = '';
}

Typescript email regexp validation

Sometimes, We want to do a validation typescript file.

  • It uses the same above regular expression pattern for email validation
  • RegExp object is created with regex
  • pattern. test checked against supplied email and return true-valid
  public isValidEmail(emailString: string): boolean {
    try {
      let pattern = new RegExp("^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$");
      let valid = pattern.test(emailString);
      return valid;
    } catch (TypeError) {
      return false;
    }
  }
}
}
console.log(this.isValidEmail('abc@gmail.com')); // true
console.log(this.isValidEmail('abc')); // false
a

Conclusion

In this post, You learned

  • Angular email pattern validation example with reactive forms
  • HTML 5 input type email form validation
  • Typescript email validation
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.