Angular custom validators + trick for flexible custom validator

Share on facebook
Share on google
Share on twitter
Share on linkedin

One of the biggest strengths of Angular is its’ forms library for handling forms logic. Even though Angular has some built-in form validators as required, it sometimes is necessary to create your own form validators.

Template driven and reactive forms

In Angular, there are two form modules: template driven and reactive.

The template-driven allows you to specify the form logic in the template and reactive allows you to write your form as typescript code in the template. This means that creating custom validators for template driven forms is gonna be slightly different from reactive forms. The difference is basically that you are gonna wrap the reactive custom validator in a directive to make it work with template driven forms. If you are using template driven forms I recommend coding your custom validators in a way that they are also compatible with reactive forms, should you want to use that.

Creating a custom validator for reactive forms

Creating a custom validator for reactive forms is actually more simple than for a template driven form. You only need to implement ValidatorFn, which takes a form control and returns an error object.

A date validator can be created as:

Here we are validating if the input can be converted to a date and if not, we return an error object with “invalidDate” set + the invalid value, this when can be used to display an error message to the user.

This validator is hooked up to a reactive form like this:

Creating a custom validator for template driven forms

As said before, when creating a custom validator for a template driven form, you should have created the validator fn first, which is used seperately if it was in a reactive form:

For using a validator in a template-driven form we hook it in with a directive. Notice that we bind to an attribute with [] in the selector. The way we hook it into Angular template driven forms by adding the directive to Angular’s NG_VALIDATORS using the multi option. NG_VALIDATORS is a provider Angular is using on every form change to loop through the validators in the form and update the form’s validity.

A validator directive implements Validator from @angular/forms which contain a validate callback which is called by Angular forms module when it iterates on all directives hooked into NG_VALIDATORS.

Input to a validator can be done with an Input validator that matches the selectors name.

A bizarre trick for creating a flexible custom validator

Alright, enough of the affiliate marketing…

I have found it could become tedious for doing all the above process for really simple validation logic, so for that reason, I came up with a custom validator directive that evaluates boolean expressions. For complex validation logic I would like to encapsulate validation logic, like in the above example, but if it is really simple boolean expressions I preferer to use the flexible custom validator, as it saves you from doing the above steps for every validator.

The flexible custom validator looks like this:

As we saw before we are creating a validationFn that is used in a directive. The directive takes as input a CustomValidator object which contains a boolean express, that is gonna be evaluated, a validator name, used in the error object.

When running the validators, you can show an error message in your template like this:

Here we are applying the custom validator in a template by passing a custom validator object containing an expression for validating the length of the input as well as the validator name used for showing validation messages:

I’m using bootstrap here for the styling.

Upon a validation error you can show something like this to a user:

Read the code for validators and more in my Angular best practices repository on Github.

Do you want to become an Angular architect? Check out Angular Architect Accelerator.

Related Posts and Comments

Walkthrough: Building An Angular App Using Tailwind CSS and Nx

In this video, we will cover a walk-through from scratch covering how to Build and Angular app using Tailwind CSS and Nx including Angular standalone components. 🖌 Tailwind CSS setup and usage⚙️ Nx monorepo configuration🧍‍♂️ Standalone components✅ Building a complete app in less than 2 hours with best practices ⏳ Timestamps:0:00 – Intro1:00 – Tailwind

Read More »

18 Performance Optimization Techniques For Angular Applications (podcast with Michael Hladky)

Performance is extremely important in front-end applications as they directly impact the application’s user experience. Poorly performing applications can be frustrating for the end-users. For example, an e-commerce site that is slow and unresponsive might deter users which could have a direct impact on the business.  Although there is a growing number of tools to

Read More »

Announcement: Angular Testing Workshop

I’m announcing a new live workshop: Angular Testing Workshop. It will be half-day workshops over three days, 100% online, where we will learn all the industry best practices with Angular testing so you can apply them in your daily work – taking straight out of my experience with doing Angular testing for big projects. The

Read More »

Server-side Rendering (SSR) with Angular Universal

As the name suggests, Single-page App (SPA) is a single HTML document that can be initially served to the client. Any new views required in the application can be created by using JavaScript solely on the client. Besides this, the request-response cycle still happens, but only to RESTful APIs to get static resources or images.

Read More »