Whenever we use a custom async validator, mostly we want to send an HTTP request to a server, and validate the input based on a response. if we navigate to the Angular Documentation, there is no information about how to inject a service into the async validator.
One possible way to inject something inside our validator function is to wrap this function with a creator function and pass parameters by ourselves.
So if I have the following validator:
I could wrap it with a creator function and pass parameters from it:
Then I could use it, somewhere in my application, like this:
new FormControl("", null, [ usernameValidator(['admin','manager']) ]);
So If I want to inject a service, I just have to pass it from the component I’m using in it.
There are some drawbacks for this solution
- It’s not loosely coupled
- We have to repeat same code, every time we use this validator
That’s why there’s a preferred way to do that.
Using a Service, for creating a Validator
So if we create some
async.service service, and declare our async validator there, we could inject
HttpClient inside this service and use it inside the async validator (it will hold the reference of
Now, all we have to do is inject this service inside a component and use it appropriately.
new FormControl("", null, [ asyncService.usernameValidator() ]);