angulartypescriptangular-reactive-formsangular-custom-validators

Angular custom validator with http don't work


I try to make a custom validator who verify that a serial number exist in my database. To do this, the custom validator must call an api endpoint. This is my custom validator

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { AbstractControl, AsyncValidator, FormControl } from '@angular/forms';
import { map, catchError } from 'rxjs/operators';
import { of } from 'rxjs';


@Injectable({
  providedIn: 'root',
})
export class HttpRequestValidation implements AsyncValidator {
  
  constructor(private http: HttpClient) {}

  validate = (control: AbstractControl) => {

    const { value } = control;
    console.log(value);
    
    return this.http.get<any>(`http://127.0.0.1/backend/api-vitoapp/verify-serial.php?serial=${value}`)
      .pipe(

        map(() => {
          return null;
        }),
        catchError((err) => {
 
          console.log(err);
          return of(true);
        })
      );
  };
}

In my component I call the validator like this

 deviceSelected : any;
  serial = new FormControl('');
  
  constructor(private fb: FormBuilder,
              private hardwareCheckService: HardwareCheckService) {
  }

  ngOnInit() {
    
    this.deviceInfos = this.fb.group({
      serial: [null, [Validators.required, this.httpRequestValidation.validate]],
      deviceType: [this. deviceTypeOptions[0]],
    });
  }

and in my template I have this

 <mat-form-field *ngIf= "deviceSelected" fxFlex="auto">
              <mat-label>Serial</mat-label>
              <input formControlName="serial" matInput required>
            </mat-form-field>

I don't understand why my serial always considered as unknown. Any idea for a Angular beginner? Thank you in advance for your help.


Solution

  • When using FormBuilder, asynchronous validators go in a second array:

    serial: [null, [Validators.required], [this.httpRequestValidation.validate]],
    

    Also, avoid mixing and matching HTML validation and reactive forms. Take the required off the input tag :-).