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
        )
      );
};
3
  • what if you change it to: result ? { titleAlreadyExists: true } : { titleAlreadyExists: false }; ? Commented Jan 30, 2023 at 23:48
  • Well, from what I understand from this official source (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." Commented Jan 30, 2023 at 23:55
  • I'm just going by the error message which says it can't be null. maybe try it. Commented Jan 31, 2023 at 0:07

1 Answer 1

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))
    );
  };
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer. I don't have the compile error anymore.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.