6
votes

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.

3
do you also want to remove validation while typing?Sumit Agarwal
I see that your are using, model driven form here. Try using reactive form module. There you can call validation manually on blur or focus.Sumit Agarwal
Template driven forum is used in my whole application . is reactive form module is only way of achieve this?Umang Patwa
yes I also want to remove validation while typingUmang Patwa
going by the link - github.com/angular/angular/issues/7113 provided by @Sam in answer below, it seems all you can do is to handle when you show the message and not the validation call (especially with Template Driven Form)Sumit Agarwal

3 Answers

9
votes

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

0
votes

This will be possible in version 5, which is not released yet.

See: https://github.com/angular/angular/issues/7113

In the meantime:

<input class="form-control" formControlName="userName" placeholder="User Name" type="text" (blur)="checkUserExists()"/>
<div class="alert-danger" *ngIf="userName.invalid && userName.touched">
  <div *ngIf="userName.hasError('required')">User Name is required</div>
  <div *ngIf="userName.hasError('userExists')">{{userName.errors.userExists}}</div>
</div>

checkUserExists() {
    if (this.userName.value) {
      this.regServ.userNameExists(this.userName.value)
      .subscribe((exists) => {
        if (exists) {
          this.userName.setErrors({ userExists: `User Name "${this.userName.value}" already exists` });
        }
      });
    }
  }
0
votes

if you are using Angular you can call in this way

<input type="text" id="sometext" (focusout)="myFunction()">

otherwise, you can use

<input type="text" id="sometext" onfocusout="myFunction()">