Create a custom validators for template driven forms and reactive forms in Angular 7

Posted at: May 27, 2019 2:07 AM

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 @angular/forms

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.

my-template-driven-form.component.ts
my-template-driven-form.component.html

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.

my-reactive-form.component.ts
my-reactive-form.component.html

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.

app.module.ts
app.component.html

Conclusion

In this lesson we have learnt to create custom validator for template-driven forms and reactive forms.

This lesson also available on YouTube
angular custom validator angular custom validator example custom validation template driven form angular 7 custom validation reactive form angular 7

Please leave comments

2 Comments