1

So, my issue is I am trying to build a custom validator on Angular 15, and I get an error message that tells this:

Type 'Observable<{ titleAlreadyExists: boolean; } | null>' is not assignable to type 'Observable'. Type '{ titleAlreadyExists: boolean; } | null' is not assignable to type 'ValidationErrors'. Type 'null' is not assignable to type 'ValidationErrors'."

This is my validator:

alreadyExistingTitle(alreadyExistingTitles: String[]): AsyncValidatorFn {
  return (control: AbstractControl): Observable<ValidationErrors> => {
    return of(alreadyExistingTitles.includes(control.value))
      .pipe(
        map((result: boolean) =>
          result ? { titleAlreadyExists: true } : null
        )
      );
};
Yong Shun
  • 35,286
  • 4
  • 24
  • 46
  • what if you change it to: `result ? { titleAlreadyExists: true } : { titleAlreadyExists: false };` ? – Rick Jan 30 '23 at 23:48
  • Well, from what I understand from this official source (https://angular.io/guide/form-validation#defining-custom-validators), the validator "takes an Angular control object and returns either null if the control value is valid or a validation error object." – Tamsin-chan Jan 30 '23 at 23:55
  • I'm just going by the error message which says it can't be null. maybe try it. – Rick Jan 31 '23 at 00:07

1 Answers1

2

Modify the return type from Observable<ValidationErrors> to Observable<ValidationErrors | null>.

alreadyExistingTitle(alreadyExistingTitles: String[]): AsyncValidatorFn {
  return (control: AbstractControl): Observable<ValidationErrors | null> => {
    return of(alreadyExistingTitles.includes(control.value)).pipe(
      map((result: boolean) => (result ? { titleAlreadyExists: true } : null))
    );
  };
}
Yong Shun
  • 35,286
  • 4
  • 24
  • 46