r/Angular2 • • Mar 24 '26

Angular signal form - Dynamic validator

Hello,

I'm hitting the wall regarding how to add a validator dynamically on a field of a signal form.

In reactive forms, you could add dynamically a validator to a form like so :

public addValidators(currentEmail: string): void {

this.form.controls.userEmail.setAsyncValidators(this.userEmailExists(currentEmail);

}

 public userEmailExists(currentEmail: string | undefined): AsyncValidatorFn {
return (input: AbstractControl) => {

const inputValue = input.value?.trim();
if (!inputValue || currentEmail === inputValue ) {
return of(null);
}

return timer(500).pipe(
distinctUntilChanged(),
switchMap(() => this.userHttpService.emailExists(input.value)),
map((exists) => {
return exists ? { emailExists: \form.error.emailExists` } : null;}),take(1),finalize(() => input.root.updateValueAndValidity({ onlySelf: true })),);}; }`

In signal form, I have something like this :

public readonly formModel = signal<UserUpdateDataForm>({
  email: '',
});

public schemaForm = schema<UserUpdateDataForm>((path) => {
  debounce(path.email, 300);
  required(path.email);

  this.myAsyncSignalValidatorService.userEmailExists(path.email);
});

public readonly form = form(this.formModel, this.schemaForm);

public readonly userChangedEffect = effect(() => {
  const currentUser = this.currentUser();

  if (currentUser) {
    this.patchForm(currentUser);
    # this.patchValidatorHereMaybe ??
  }
});

The idea is that I would like to add the validator to the signal form whenever a signal input "user" is provided on my form component. If no user input is provided, it means that I'm creating a new user therefore I dont have a "currentEmail" and the signal form schema would already provide the async validator

1 Upvotes

6 comments sorted by

View all comments

Show parent comment

2

u/Wildosaur Mar 25 '26

I can understand why they want to avoid "setAsyncValidators" and see the benefits of not going the imperative way but as you say, it might be a bit too strict. However I think we'll get used to it at some point and never look back.

As you suggested, I extract the validation into a function with a linked rxResource and this is perfectly fine even though the documentation is out of date on some parts and I guess there are fixes needed to handle correctly the non run part of an async validator (see my comment on undefined).

const userEmailExistsResource = (emailSignal: Signal<string | undefined>): ResourceRef<boolean | undefined> => {
  const userHttpService = inject(UserHttpService);

  return rxResource({
    // NG doc states we should use "request" but only "params" exists
    params: () => emailSignal(),
    stream: ({ params: username }) => userHttpService.isEmailTaken(username),
  });
};

export const userEmailExistsAsync = (field: SchemaPath<string>, initialValueSignal: Signal<string>): void => {
  validateAsync(field, {
    params: ({ value }) => {
      const val = value().trim();
      const initialVal = initialValueSignal()?.trim();

      if (!val || val === initialVal) {
        return ''; // We should return undefined instead in order not to trigger rxResource however this bugs out the compiler for now ..
      }

      return val;
    },
    factory: userEmailExistsResource,
    onSuccess: (result) => {
      if (result) {
        return {
          kind: 'emailExists',
        };
      }
      return null;
    },
    onError: (_error) => {
      return {
        kind: 'networkError',
        message: 'Could not verify email availability',
      };
    },
  });
};

3

u/MichaelSmallDev Mar 25 '26 edited Mar 25 '26

Interesting, I like the resource use for this.

Btw, I made a PR to update the docs with respect to `params`: https://github.com/angular/angular/pull/67860

edit: I see you made an issue about the undefined value, nice work

3

u/Wildosaur Mar 25 '26

Thanks for the PR regarding the doc, I was about to do it !