Angular, Web

Custom control validation in Angular

3 min read

Validation is an integral part of a web application. Making sure that a first validation pass is done on the client side can (to some extent) help you cleanse your data and show useful messages to your users when the input data is invalid. Angular comes with a pre-determined set of validators, and you can find find some validators libraries on GitHub, but sometimes this is not enough as you need custom rules for validating your data. Since form validation can occur through reactive forms or template driven forms, let’s go over each of them to see how we can add a custom validator in each case.

Custom validator through reactive forms

Validation can occur on a formControl or on a formGroup. As you know, you can create a formGroup through the FormBuilder class that you inject into your component.

The same can be done without the FormBuilder class however.

A validator needs to return (or be) a function that takes an AbstractControl as input and returns an object where the key is a string and value is anything(a.k.a object):

(control: AbstractControl): {[key: string]: any}

The key of the return object is usually the validatorName, but can be what you desire. The key is the property that will reside in the errors object of the formControl/formGroup control that can be accessed through the hasError() method. Angular checks if the control/group is in error if a key exists in its errors dictionary and if the value of that key is evaluates to true.

When building a validator, I like to check if the required validator already exists and just return that the validator is valid. This is just for comfort and eases out an extra processing for nothing. When the required validator is present, it usually mean that the user has yet to input data, so we know that our validator won’t be valid anyway.

For the sake of the example, we will create a custom validator that checks if the input is a valid ISO 8601 (yyyy-mm-dd) date and if that date is the end of the month.

For simplicity reasons, I added all the testing functions in the file, but isEndOfMonth, for instance, could have been an extension of the Date object (Date.prototype)

We can now add the validator to our control/group and change the dob control from new FormControl('',[Validators.required]) to new FormControl('',[Validators.required,dateIsEndOfMonth]).

Now assume we want to pass a pre-defined parameter to our validator. We can do so by creating a factory method: a method wrapper that will return the validator function based on some input. Here is an example where one would want to create a validator function to accept a parameter. This can be useful when you would want for instance have a custom regular expression to test the data input.

This example below checks that the input is an odd number, but allows for certain even numbers to be entered.

Custom validator through template driven forms

In template driven forms, we don’t have access to the FormControl directly. As such we have to wrap our validator function (above) in a directive.

The class implements the interface Validator from @angular/forms. In the above implementation, the validator is valid on inputs of type text with the following characteristics: they are form controls or they implement the ngModel directive. This is obviously a basic example. If you are curious, you can look at how some validators that angular provide are built here.

Note that the @Input variable is of type string as it’s parsed directly from the template. In my example for the isOddWithEvenAllowed directive, my parameter to my directive was “18,24,36” and not “[18,24,36]” and i’m casting the former to an array of numbers and passing the result to my function. This is because the parameters of the directive is a string.

You can find a working example of the implementation of the 2 types above with 2 plunkrs I made: reactive forms and template driven.

On the way to validation!

You should be now able to create custom validators for your validations. As always you can always refer to Angular’s documentation on the subject for more guidance. Happy validation!