Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Async Form Validation with Injected Providers

I have a custom async validator in a reactive form that needs to call out to a service to validate whether a name is unique.

Since validators are pure functions, there doesn't seem to be a good way to inject a provider such as HTTP to make these calls.

The code I currently have is returning a function that passes the service but this feels a tad hacky...

export function nameValidator(platformService: PlatformService): ValidatorFn {
    return (control: FormControl): { [key: string]: any } => {
        return userService.getUnique(control.value)
    };
}

my question is there a better way?

like image 203
amcdnl Avatar asked Feb 05 '26 16:02

amcdnl


1 Answers

Validators can be injectable directive classes when being used as directives in templates.

They are expected to be functions when they are specified directly in FormControl or FormBuilder

In order to make use of DI they should be useFactory or useClass providers and injected into a component:

@Injectable()
class NameValidator implements AsyncValidator {
  constructor(private userService: UserService) {}

  validate = (control: FormControl) => this.userService.getUnique(control.value);
}

...

new FormControl('', nameValidator.validate);

Notice that validate method is passed as a callback and should be either an arrow or be bound to class instance with bind.

like image 142
Estus Flask Avatar answered Feb 07 '26 10:02

Estus Flask



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!