Reactive Form Validation in Angular 6

Introduction

In this article, we will implement validation in a reactive form. So, Before proceeding further, I would recommend that you will understand. How to create an angular application and configure the route URLs.

Add Validation

Now, we will implement the example in a previously created application. So, we want to make the full name field a required field. If, we don’t type anything in the full name field. Then, you want to display a validation message like “this full name is required”. and we also want to validate the minimum and the maximum number of characters. that, we can type into the field minimum length is 2 and the maximum is 10.

For example, if, the user types one character. then, we want to display this validation error message full name. it must be greater than 2 characters and less than 10 characters. and if, the correct number of characters then the validation message should disappear. if, we insert more than 10 characters. then the same validation message should appear again.

when implementing validation in a reactive form. the first thing, that, we do is import angular’s validators class. this class is present in angular’s forms package.

Add Validators class

So, let’s add validators class. inside, the create-employee-component.ts.

import { Validators } from ‘@angular/forms’;

Validator Functions

The validators class as the name implies provides several validator functions.

1] Required:
the name implies it validates that a field has a value. for example, the full name is required.

2] RequiredTrue:
this function validates a field value is true. it’s commonly used on a required checkbox. for example, we have a registration page and on that page, we want to make sure the user has checked. that checkbox before enabling the submit button. so, this is one use case where we could use this function next.

3] Email:
The name implies this validator. ensures the control value matches a valid email pattern.

4] Pattern:
The pattern validates field value matches the specified regular expression pattern.

5] Min:
This validates that a field value is greater than or equal to a provided number. for, example the minimum age to vote is 18.

6] Max
this validates that a field value is less than or equal to a provider number. for, example people over the age of 90 are not eligible for this insurance policy.

7] minLength
this validates the number of characters in a field must be greater than or equal to the provided minimum length. for, example full-name must be at least two characters opposite to min length.

8] maxLength:
The number of characters in a field is less than or equal to the provided maximum length. for example, full-name cannot exceed 10 characters.

Add Validation Methods

Now, let’s go to create-employee-component.ts file.
for validating the full name field.

we are going to use three functions in our component class.

1.Required
2.minLength
3.maxLength

Here, we have a FullName form control in the following example.

this.employeeForm = this.fb.group({
fullName: [”, [Validators.required, Validators.minLength(2), Validators.maxLength(10)]],
});

The creating a form control. so, we specify a key-value pair. The key is the name of the form control and value is an array of the first element.

The required function provided by validators class. Now, one important thing to keep in mind is, all these valid data functions are static functions.

So, we have empty form fields. here, our FullName form control valid property is false. we made this full name form control required and we don’t have a value supplied.

reactive form valid property

If, we supply a value to the fullName field then the property value changes to true

property value changes in reactive form validation

Add Bootstrap class

Now, let’s go to create-employee-component.html file element in the template. so, we have our full name and email fields.

After that, we want to use the bootstrap has-errors class to style the form control differently. if, there are validation errors. so, we want to dynamically add and remove has-error bootstrap CSS class.

<div class="form-group"
      [ngClass]="{'has-error': ((employeeForm.get('fullName').touched ||employeeForm.get('fullName').dirty) && employeeForm.get('fullName').errors)}">

The div element, we are going to make use of the angular class binding. so, we use ngClass directive.

Now, the bootstrap styling class that we want to dynamically add or remove is has-error.

So, let’s use this property and to retrieve a form control that is present inside a form group. we can use the get method of the form group and to this method specify the name of the form control.

[ngClass]=”{‘has-error’:employeeForm.get(‘fullName’).errors}”

within the get method and then we can use the errors property, to see, if there are any validation errors on the full name form control.

another touch validation property. it is false that, we didn’t even have the opportunity to touch the form or this full name input field and even before, that the field color has changed to red, it indicating the fields to turn red. they touched the field and left the field without providing a valid value.

[ngClass]=”{‘has-error’:employeeForm.get(‘fullName’).touched}”

we can very easily achieve that using dirty and touched properties. so, we want this has at a class to be applied when the full name form control has errors and when the form control is touched or it is dirty so when the full name form control has errors and it’s touched or dirty then add this has error class.

[ngClass]=”{‘has-error’:employeeForm.get(‘fullName’).touched}”
|| [ngClass]=”{‘has-error’:employeeForm.get(‘fullName’).dirty}”

After that, display validation error message for the full name is required. after the full name input element. let’s, include a span element and the error message is full name is required and we don’t want to display the span element all the time. so, let’s use ngIf structural directive.

<div class="form-group"
      [ngClass]="{'has-error': ((employeeForm.get('fullName').touched ||
                                 employeeForm.get('fullName').dirty) &&
                                 employeeForm.get('fullName').errors)}">
  <label class="col-sm-2 control-label" for="fullName">Full Name</label>
  <div class="col-sm-8">
    <input id="fullName" type="text" class="form-control" formControlName="fullName">
    <span class="help-block"
          *ngIf="((employeeForm.get('fullName').touched ||
                   employeeForm.get('fullName').dirty) &&
                   employeeForm.get('fullName').errors)">
      <span *ngIf="employeeForm.get('fullName').errors.required">
        Full Name is required
      </span>
    </span>
  </div>
</div>

Now, again let’s add span element for minLength and maxLength validation on our full-name form control so within this full name input field. we want a minimum of 2 characters, but not exceeding a maximum of 10 characters. so, in the component class along with the required validator on this full name form control.

<div class="form-group"
      [ngClass]="{'has-error': ((employeeForm.get('fullName').touched ||
                                 employeeForm.get('fullName').dirty) &&
                                 employeeForm.get('fullName').errors)}">
  <label class="col-sm-2 control-label" for="fullName">Full Name</label>
  <div class="col-sm-8">
    <input id="fullName" type="text" class="form-control" formControlName="fullName">
    <span class="help-block"
          *ngIf="((employeeForm.get('fullName').touched ||
                   employeeForm.get('fullName').dirty) &&
                   employeeForm.get('fullName').errors)">
      <span *ngIf="employeeForm.get('fullName').errors.required">
        Full Name is required
      </span>
      <span *ngIf="employeeForm.get('fullName').errors.minlength ||
                   employeeForm.get('fullName').errors.maxlength">
          Full Name must be greater than 2 characters and less than 10 characters
      </span>
    </span>
  </div>
</div>

So, the component class gives us a lot more flexibility both in terms of unit testing. we want to load those validation error messages. and also how to implement angular reactive form validation.

Leave a Reply

Your email address will not be published. Required fields are marked *