The Angular Custom Directive For Reactive Form Validation

Vaibhav Patil
3 min readJun 2, 2019

--

Angular custom directive

In regular form validation, we validate the form using a reactive form’s custom validation or pattern validation. In the custom validation, it’s difficult to write reusable code as compared to directives. The above statement is an arguable statement, but with my experience it’s true. The use of directive for form validation is a very simple & preferred way in angular.

By using a custom directive for form validation, you can write code at a single time & use that throughout the project without repeating the same code of block in multiple files. In this article, we will discuss whitespace validation for reactive forms but you can write any kind of form validation directives. So without discussing any more comparison or theoretical part, we will focus on code.

The code of custom whitespace validation directive is as below,

import { Directive, Input } from '@angular/core';
import { AbstractControl } from '@angular/forms';
import { CustomValidators } from '../common-services/custom-validators';

@Directive({
selector: '[validateWhitespace]'
})
export class WhitespaceDirective {
@Input('validateWhitespace') validateWhitespace: AbstractControl;
constructor() { }

ngAfterViewInit(): void {
if (this.validateWhitespace) {
const oldValidator = this.validateWhitespace.validator;
if (oldValidator) {
this.validateWhitespace.setValidators([this.noWhitespaceValidator, oldValidator]);
return;
}
this.validateWhitespace.setValidators([this.noWhitespaceValidator]);
}

}
noWhitespaceValidator(control: AbstractControl) {
if (typeof control.value === 'string') {
let whitespace: boolean = false;
if (control.value !== '') {
whitespace = (control.value || '').trim().length === 0;
}
return whitespace ? { whitespace } : null;
}
}
}

Create a separate module for custom directives because we can import that module into where we required the custom form validation.

@NgModule({
declarations: [WhitespaceDirective],
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule
],
exports:[WhitespaceDirective]
})
export class CustomValidatorModule { }

For implementing above whitespace form validation directive into your form. We have to first import the “CustomValidatorModule” into the module which contains the form where we want to implement whitespace validation.

@NgModule({
declarations: [TestingFormValidationComponent],
imports: [
CommonModule,
TestingFormValidationRoutingModule,
FormsModule,
ReactiveFormsModule,
CustomValidatorModule
]
})
export class TestingFormValidationModule { }

After importing the “CustomValdationModule” next step to implement the directive into our form. For that, we have to use the directive selector “validateWhitespace” as an attribute into HTML and pass the FormControl object of a form field for which you want to implement whitespace validation.

<form [formGroup]="addComplaintAndFeedbackForm" [style.fontSize.px]="10">
<div class="container-fluid">
<div class="row">
<div class=" col-sm-12 col-md-2 col-lg-2 col-xl-2">
<input matInput placeholder="Complaint Status" formControlName="complaintStatus" required [validateWhitespace]="addComplaintAndFeedbackForm.get('complaintStatus')">
<span *ngIf="!addComplaintAndFeedbackForm.get('complaintStatus').hasError('required') && addComplaintAndFeedbackForm.get('complaintStatus').hasError('whitespace')">Whitespace not allowed</span>
<span *ngIf="addComplaintAndFeedbackForm.get('complaintStatus').hasError('required')">Complaint Status is required</span>
</div>
</div>
</div>
</form>

That’s over, now you can use the attribute “validateWhitespace” by importing the module into where you want to required whitespace validation. As mentioned at the start of this article, you can write any type of custom form validation directive and use it to check validation into your form.

Thank you for giving you valuable time for reading this article… I hope this article is useful to you.

--

--