Issue
I am trying to make a custom validator for my Angular 9 project.
this is the validator method
public static validatName(service: MyService): AsyncValidatorFn {
return (control: AbstractControl): Observable<ValidationErrors> => service.searchNumber(control.value)
.pipe(
map((response) => response ? null : { notFound: true })
);
}
when the server response with a 404 error code, the map it’s not executed and my form control doesn’t get the validation null/not found needed.
How can I map my server response, either 200 success or any error.
When I get 200 it should retrieve null otherwise notFound: true
At the moment, only the 200 status code scenario works
Solution
You need to catch an exception.
public static validatName(service: MyService): AsyncValidatorFn {
return (control: AbstractControl): Observable<ValidationErrors> => service.searchNumber(control.value)
.pipe(
map((response) => null),
catchError(() => of({ notFound: true })), // here
);
}