Custom Validator with Parameters in Angular

Learn how to create a custom validator with parameters in Angular Reactive Forms. This is the continuation of our previous tutorial, where we learned how to build a custom validator in Reactive forms.

Custom Validator with Parameter

Here is the code of greater than validator (gte) from the Custom Validators in Angular Reactive Form tutorial. The validator checks if the given value is greater than 10 and if not return ValidationErrors.

The problem with the above validator is that the value 10 is hardcoded. Hence, we will be not able to reuse it. If we want to resue it, we need to pass the number as the parameter.

Let us add the parameter val:number to the validator as shown below.

The compiler immediately throws an error as shown below.

That is because, the Validator must implement ValidatorFn Interface. It can have only one parameter i.e control: AbstractControl

Passing Parameters to a Custom Validator

To pass a parameter, we need to create a factory function or a function that returns a function. The example code is as shown below

First, we create a factory function. It receives the val as the argument. It must return the function of the type ValidatorFn

The get must return a function ValidatorFn

Using the Validator

Now, add the validator to the Validator collection of the FormControl as shown below

Accessing the Errors in Template

Summary

We learned how to pass a parameter to a custom validator. First, we create a factory function, which accepts the parameter. The factory function returns the validator function. Using this technique we can pass as many as parameters to a custom validator in Angular.

1 thought on “Custom Validator with Parameters 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