Fire validation when focus out from input in angular?

北城以北 提交于 2019-12-07 16:59:12

问题


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


来源:https://stackoverflow.com/questions/46297130/fire-validation-when-focus-out-from-input-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!