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.

Applies to: Angular 2 to the latest edition of i.e. Angular 8. Angular 9, Angular 10

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


Best Angular Books
The Top 8 Best Angular Books, which helps you to get started with Angular  

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.

Scroll to Top