-->

Fire validation when focus out from input in angul

2019-05-21 00:06发布

问题:

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.

回答1:

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



回答2:

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` });
        }
      });
    }
  }