Inject Service Into Validator in Angular

Learn how to inject service into Validator in Angular. The validator may depend on some external service to do its validation. For Example, it may need to fetch data from the back end server to validate the value.

This is a continuation of our following tutorials

  1. The custom validator in Angular
  2. Angular custom Validator with Parameters

Custom Validator

Here is our greater than custom validator gte from the previous tutorial. The gte is a function that returns ValidatorFn function.

We pass the parameter to the validator in the component class as shown below.

Validator Service

Let us now see how we can inject service into the above validator. First, move the logic from the gte validator to a separate service.

Create a new service gte.service.ts

The gteService is very simple.

The gte method takes val and requiredValue as the parameter. It checks if the val is a number and is greater than requiredValue. If yes returns true else returns false.

Injecting Service

There are two ways you can inject service into the validator. One is to create a wrapper service. The other option is to inject service directly into the validator.

Wrapper Service

Open the gte.validator.ts. Create the gteValidatorService class. In the constructor inject the gteService. Copy the validator functiongte into the class and use the gteService as shown below

Inject the gteValidatorService in the component class and use the validator as shown below.

Inject Service directly into the Validator

Another option is to directly inject the service into the Validator as shown below.

We use the Injectorto inject the instance of the service.

Summary

In this article, we learned how to inject the service into the validator function. One option is to create a Validator service. Copy the validator function into the Validator service. Another option is to inject the service directly into the validator function using the inject method.

Complete List of Angular Forms Tutorial

  1. Angular Forms Tutorial: Fundamental & Concepts
  2. Template Driven Forms in Angular
  3. Set Value in Template Driven forms in Angular
  4. Reactive Forms in Angular
  5. FormBuilder in Reactive Forms
  6. SetValue & PatchValue in Angular
  7. StatusChanges in Angular Forms
  8. ValueChanges in Angular Forms
  9. FormControl
  10. FormGroup
  11. FormArray Example
  12. Build Dynamic or Nested Forms using FormArray
  13. Validations in Reactive Forms in Angular
  14. Custom Validator in Reactive Forms
  15. Passing Parameter to Custom Validator in Reactive Forms
  16. Inject Service into Custom Validator
  17. Validation in Template Driven Forms
  18. Custom Validator in Template Driven Forms

1 thought on “Inject Service Into Validator in Angular”

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top