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.