I have a custom validator who verify that a serial number exist in my database. I would like to display an specific error message in the field of the form when the serial is not found but I can't do it. I tried different methods but the result is not good. When I try to insert this code in my template
<div *ngIf="deviceInfos.controls.serial.errors && serial != null">
Error
</div>
The error message is displayed even before the user enter in the field. I'm new in Angular and I'm actually lost in that problem.
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 (err);
})
);
};
}
And this is the part of my component
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]],
});
}
Can someone help me? Many thanks in advance.