2

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];
    }
);
4
  • is the validator called? is your selector working? Commented Jun 5, 2019 at 13:36
  • Yes it is being called, and the selector works when I do subscribe. Commented Jun 5, 2019 at 13:37
  • I think its because this._existUser() is an async validator and should passed as the third argument Commented Jun 5, 2019 at 14:32
  • That was the problem, can you post here the solution for me to place as resolved? Thank you! Commented Jun 5, 2019 at 15:30

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

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.