Using validation functions that work with both template-driven and reactive forms

Yesterday, we looked at how to write a validation function that works with reactive forms. Template-driven forms have a somewhat similar approach that also uses a validator function but requires a wrapper directive that implements the Validator interface like this one (example here):

The easiest solution to write a validation function that works with both reactive forms and template-driven forms is to create a directive for the template-driven form validation and then expose the validation function as a static method of that class:

A static method has two advantages in that scenario:

  • It’s public
  • It does not require an instance of the class (we can refer to it as CreditCardValidator.validateCcNumber)

As a result, we’d use our validation feature like this in a template-driven form:

And like that in a reactive form:

You can check the complete code for that example on Stackblitz here. Here is another tutorial for more information on that validation approach.

Alain Chautard

Alain is a Google Developer Expert in Web Technologies, Angular, and Google Maps. His daily mission is to help development teams adopt Angular and build at scale with the framework. He has taught Angular on all six continents! A world traveler and photographer, Alain is also an international conference speaker, and a published author of several video courses.