3

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?

1 Answer 1

5

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.

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.