Angular has some predefined built-in validators for form. For email, there are predefined Validators.email validator. It doesn't work as expected and misses some basic validation. In some cases, custom validation is needed to achieve the desired outcome. So in this post, a custom email validator is used to validate the email.
Instead of validators.email use regex pattern like Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$'). In the component typescript file use the regex pattern.
The required property denotes the email input field is mandatory and cannot be left empty.
EmailComponent:
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class EmailComponent {
title = 'Angular Form Email Validation';
form = new FormGroup({
email: new FormControl('', [Validators.required, Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$')]),
});
get f() {
return this.form.controls;
}
submit() {
if (this.form.status === 'VALID') {
console.log(this.form.value);
}
}
}
HTML File
<h1 style="padding-left:10px;">Angular Form Email Validation</h1>
<form [formGroup]="form" (ngSubmit)="submit()" style="padding-left:10px;">
<div class="form-group">
<label for="email">Email</label>
<input formControlName="email" id="email" type="text" style="width:300px;" class="form-control">
<br>
<div *ngIf="f.email.touched && f.email.invalid" class="alert alert-danger" style="width:300px;">
<div *ngIf="f.email.errors.required">Email is required.</div>
<div *ngIf="f.email.errors">Please, enter valid email address.</div>
</div>
</div>
<button class="btn btn-primary" type="submit">Submit</button>
</form>
To run this example, use ng serve command and make sure the EmailComponent is declared in App Module.