Vinutha K Shetty
Vinutha K Shetty

Reputation: 307

Angular - Email pattern validation

<label for="userEmail">User Email:</label><br />
<input type="email" class="userMobile" id="userEmail" name="userEmail"
  [(ngModel)]="selectedLocker.lockeruseremail" required 
  pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.(com|in)$"/><br />

The pattern requires the email to be in the format "[email protected]" or "[email protected]", but it still allows submission without ".com" or ".in".

Upvotes: 2

Views: 131

Answers (2)

Yong Shun
Yong Shun

Reputation: 51450

For the template-driven form, you should use form.valid to check the form is valid before submission. And apply the [disabled] attribute to block the button submission.

import { ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';

@ViewChild('form') form!: NgForm;

submit() {
  if (!this.form.valid) {
    alert('Form value invalid Detected!')
    return;
  }

  ...
}

You can display the error for the control with the ngModel directive as below:

<form #form="ngForm" (submit)="submit()">
  <label for="userEmail">User Email:</label><br />
  <input
    type="email"
    class="userMobile"
    id="userEmail"
    name="userEmail"
    [(ngModel)]="selectedLocker.lockeruseremail"
    required
    pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.(com|in)$"
    #email="ngModel"
  /><br />
  <ng-container *ngIf="email.errors?.pattern">
    Invalid email pattern.
  </ng-container>

  <button [disabled]="!form.form.valid">Submit</button>
</form>

Demo @ StackBlitz

Upvotes: 2

Yassin Mo
Yassin Mo

Reputation: 610

This email validation pattern has several issues, try to use this pattern :

^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$

Upvotes: -1

Related Questions