Create a custom validators for template driven forms and reactive forms in Angular 7
In this lesson we will learn, how to create custom validator for template-driven forms and reactive forms in Angular 7.
Create a Directive
I have created a directive EvenNumberValidatorDirective in shared folder for validate even number.
Need to import few modules AbstractControl, NG_VALIDATORS, Validator, ValidationErrors from
AbstractControl: It provides some of the shared behavior that all controls and groups of controls have, like running validators, calculating status, and resetting state. We get a
AbstractControl as parameter to validate() function for access the field value to check for control states such as valid and dirty.
If field value is valid then
validate() function return null otherwise return an object with property
appEvenNumberValidator to set true.
NG_VALIDATORS: Registers a custom validator directive. Adding the validator to the existing collection of validators requires the multi: true option.
Validator: It is an interface for implemented by any classes for performing synchronous validation.
validate() method that performs synchronous validation against the provided control.
ValidationErrors: If validation failed to then return validation errors.
ValidationErrors | null A map of validation errors if validation fails, otherwise null.
Custom validation in Template-driven Form
I have created a template-driven form with two fields name and num for check custom validation. For example, I have created a component MyTemplateDrivenFormComponent.
In template-driven form, I have specified appEvenNumberValidator directive selector attribute in num filed for check custom validation even number also I have checked this field for required.
Custom validation in Reactive Form
I have created a reactive form with two fields name and num for check custom validation. For example I have created a component MyReactiveFormComponent.
In reactive form, I have specified appEvenNumberValidator directive selector attribute in num filed for check custom validation even number also I have checked this field for required.
In this lesson we have learnt to create custom validator for template-driven forms and reactive forms.