Search code examples
angularngrxangular-reactive-forms

async validation reactive forms angular with ngrx


I need to validate if the user exists in the state of my application. In my application I'm using ngrx and through a selector I want to validate if the user exists.

How can I do this?

I'm not able to validate this way, what am I doing wrong?

return this._formBuilder.group({
  id: ['', this._existUser()],
  dateStart: ['', Validators.required],
  dateEnd: ['', Validators.required]
})

  private _existUser(): AsyncValidatorFn {
    return (control: AbstractControl): Promise<{ [key: string]: any } | null> | Observable<{ [key: string]: any } | null> => {
      const userId = control.value;
      return this._store.select(usersSelectors.getUserById, { id: userId}).pipe(
        debounceTime(500),
        take(1),
        map(value => {
          // Not entering the map...
          return !!value ? { invalid: true } : null;
        })
      )
    };
  }

selectors.ts:

export const getUserById = createSelector(
    selectEntities,
    (entities, props): any => {
        return entities[props.id];
    }
);

Solution

  • The problem is that you defined this._existUser() as second parameter which is for validators or options, async-validators have to be passed as third parameter

    return this._formBuilder.group({
      id: ['', [], this._existUser()],
      dateStart: ['', Validators.required],
      dateEnd: ['', Validators.required]
    })
    

    https://angular.io/api/forms/FormControl