How to fire Angular 5 async validator onblur for FormGroup

BSimpson picture BSimpson · Nov 9, 2017 · Viewed 13.4k times · Source

I am using Angular version 5.0.1 and I'm trying to fire an AsyncValidator on a FormGroup on a blur event on one of the FormControls in the FormGroup.

I can get onBlur to work on a form control using the following:

name: ['', {updateOn: 'blur'}]

However, when I try to apply it to a FormGroup it doesn't work.

Is it possible to only fire an AsyncValidator onBlur on a FormGroup, and if not, what is the best way to execute the validator only when the user has finished entering data?

My only other option at the moment is to us some sort of debounce wrapper for my validator.

Just reading through here and it appears I should be able to use updateOn: 'blur' for a form group.

After new FormGroup(value, {updateOn: 'blur'})); new FormControl(value, {updateOn: 'blur', asyncValidators: [myValidator]})

Answer

vts picture vts · Jan 4, 2018

In Angular5 Specifying the update mode is possible for both types of forms: template-driven forms and reactive forms.

First one is working for you. Here's the working example for reactive forms

Component.ts

 import { Component, OnInit } from '@angular/core';
    import { FormGroup, FormControl, Validators } from '@angular/forms';
    @Component({
      selector: 'form01',
      templateUrl: './student.component.html',
      styleUrls: ['./student.component.scss']
    })
    export class StudentComponent implements OnInit {
    formTitle:string="Student registration ";
    nameForm: FormGroup;

    constructor() {
    }

    ngOnInit() {
      this.nameForm = new FormGroup ({
        firstname: new FormControl('', {
          validators: Validators.required,
          asyncValidators: [yourAsyncValidatorFunction],
          updateOn: 'blur'
        }),
        lastname: new FormControl('', {
          validators: Validators.required,
          asyncValidators: [yourAsyncValidatorFunction],
          updateOn: 'blur'
        })
      });
    }
    }

HTML

<form [formGroup]="nameForm" novalidate>
  <div class="form-group">
    <label>What's your first name? </label>
    <input class="form-control" formControlName="firstname">
  </div>
  <div class="form-group">
    <label>What's your last name?</label>
    <input class="form-control" formControlName="lastname">
  </div>
  <button type="submit" class="btn btn-success">Submit</button>
</form>

  <h3>Hello {{nameForm.value.firstname}} {{nameForm.value.lastname}}</h3>