Fire validation when focus out from input in angular?

Umang Patwa picture Umang Patwa · Sep 19, 2017 · Viewed 11.4k times · Source

Email validation is being fired as we keep typing in textbox. I want this validation to be fired when user focuses out of the textbox

Below is my code:

<input class="form-control" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$"
 name="Email" type="email" [(ngModel)]="model.Email" #Email="ngModel" required>

<div class="red" *ngIf="Email.errors && (Email.dirty || Email.touched)">
     <div [hidden]="!Email.errors.pattern">
         Please enter a valid email.
     </div>
</div>

Please suggest me how can I achieve this. Thanks in advance.

Answer

mikhail-t picture mikhail-t · Nov 15, 2018

Starting with the version 6+ form field validation can be set via updateOn property.

With template-driven forms:

<input [(ngModel)]="name" [ngModelOptions]="{updateOn: 'blur'}">

With reactive forms:

new FormControl('', {updateOn: 'blur'});

And if you have validators set:

new FormControl('', {validators: [Validators.required, Validators.email], updateOn: 'blur'})

Source: https://angular.io/guide/form-validation#note-on-performance