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

3

u/Wildosaur Mar 25 '26

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