r/Angular2 • u/Wildosaur • 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
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).