Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How call async validator function on blur in angular reactive form builder?

My async validation function call on every keyup event. How to call async function on blue event.
Registration Component Code::

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

import { UserService } from '../../services/user.service';
import { ApiError } from '../../models/apierror';
import { UniqueUsername } from '../class/unique-username';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css'],
})
export class RegisterComponent implements OnInit {
  error!: ApiError;
  submitted = false;

  registrationForm!: FormGroup;

  constructor(
    private fb: FormBuilder,
    private router: Router,
    private userService: UserService,
    private uniqueUsername: UniqueUsername
  ) {}

  ngOnInit(): void {
    this.registrationForm = this.fb.group({
      name: ['', Validators.required],
      username: [
        '',
        [Validators.required],
        [this.uniqueUsername.validate.bind(this.uniqueUsername)],
      ],
      password: ['', Validators.required],
    });
  }

  get name() {
    return this.registrationForm.get('name');
  }

  get username() {
    return this.registrationForm.get('username');
  }

  get password() {
    return this.registrationForm.get('password');
  }

  onSubmit() {
    const formData = new FormData();
    formData.append('name', this.registrationForm.get('name')!.value);
    formData.append('username', this.registrationForm.get('username')!.value);
    formData.append('password', this.registrationForm.get('password')!.value);
  }

  gotoHome() {
    this.router.navigate(['/']);
  }
}

Async Validator class code::

import { Injectable } from '@angular/core';
import {
  AbstractControl,
  AsyncValidator,
  ValidationErrors,
} from '@angular/forms';
import { Observable, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';

import { UserService } from '../../services/user.service';

@Injectable({ providedIn: 'root' })
export class UniqueUsername implements AsyncValidator {
  constructor(private userService: UserService) {}

  validate(control: AbstractControl): Observable<ValidationErrors | null> {
    const { value } = control;
    return this.userService.checkUsername(value).pipe(
      map((isExist: boolean) => (isExist ? { uniqueUserName: true } : null)),
      catchError(() => of(null))
    );
  }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Combine AbstractControlOptions with FormBuilder:

 this.registrationForm = new FormGroup(
   this.fb.group({
     name: ['', Validators.required],
      username: [
        '',
        [Validators.required],
        [this.uniqueUsername.validate.bind(this.uniqueUsername)],
      ],
      password: ['', Validators.required],
   }).controls, {
     updateOn: 'blur'
   }
 );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading