Home > Net >  Type 'null' is not assignable to type 'ValidationErrors'
Type 'null' is not assignable to type 'ValidationErrors'

Time:01-31

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
          )
        );
  };

CodePudding user response:

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))
    );
  };
}
  • Related