ANGULAR FORM VALIDATIONS




As we had already gone completed on Forms blog, now we can check how to implement validations in Angular

In the Template-driven approach, it is fully dependent on the HTML part and there is no dependency on the model or component.

Whereas, while coming to the Reactive approach, it is fully dependent on the component and we will pass all our validations to our  HTML Page. 

Now, we will create a template-driven approach form now and then we will go for the reactive approach.

Angular Template-driven forms validation

For template-driven approach forms validation, we need to use all the methods which we can use for the HTML  native forms.

Now we will go through an example

This below element will show the validation required, minLength.

<input id="name" name="name" class="form-control"
       required minlength="4" forbiddenName="bob"
       [(ngModel)]="hero.name" #name="ngModel" >

Now, whenever we would like to show a message for a particular textbox, we need to use methods like dirty, invalid, and touched.

<div *ngIf="name.invalid && (name.dirty || name.touched)" class="alert alert-danger">

<div *ngIf="name.errors.required">
   Name is required.
</div>

<div *ngIf="name.errors.minlength">
   Name must be at least 4 characters long.
</div>

<div *ngIf="name.errors.forbiddenName">
   Name cannot be Harikirshnan
</div>
</div>

As I already told, we need to apply HTML validations to methods like Minimum-length., Required.

#name=”ngModel”, which will apply NgModel into a local variable called name. We need to use this way to get the state is valid or dirty.

Next, I will show you all the respective validation methods, we need to use ngIf directive with a form control method and it is respective validation methods.

Angular Reactive forms validation

Reactive forms are completely driven by validations and components which will be defined all in the component itself.

Let us define a form as simple and it`s  corresponding validations

app.component.ts

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'Angular Sample Reactive Forms';
  simpleForm: FormGroup;
  ngOnInit() {
    this.simpleForm = new FormGroup({
      'name': new FormControl(null, Validators.required),
      'desc': new FormControl(null, Validators.required),
    });
  }
  saveData(){
  }
}

Now,

Now on the first, we will start importing the corresponding module into our component.

The middle part of the @Component decorator has,

In the part section, our class has defined a simple form as a FormGroup which will be having a number of members that are FormControl.

In reactive forms approach, this way we can define the form group method and their corresponding form-controls for structuring the forms and it’s corresponding validations.

Now we will do,  how we will implement the actual HTML form in the template.

app.component.html

Now here, we will define a simple HTML form with corresponding FormControl and FormGroup.

<form [formGroup]="simpleForm" (ngSubmit)="saveData()">
<div class="row">
  <div class="col-md-4">
    <div class="form-group">
      <label for="name">Name: </label>
      <input type="text" formControlName="name" class="form-control">
    </div>
    <p class="help-block" *ngIf="!simpleForm.get('name').valid && simpleForm.get('name').touched">Please Enter Your Name.</p>
  </div>
</div>

<div class="row">
  <div class="col-md-4">
    <div class="form-group">
      <label for="desc">Desc: </label>
      <input type="text" formControlName="desc" class="form-control">
    </div>
    <p class="help-block" *ngIf="!simpleForm.get('desc').valid && simpleForm.get('desc').touched">Please Enter the Description.</p>
  </div>
</div>
</form>

First, we have defined the corresponding form with the formGroup named as `simpleForm` in that we have already defined in the component.

Second, we have the form controls as formControlName in which we have also defined in our component as the FormControl.

Third and final is we need to show the validations by using the corresponding default methods like touched, valid, and dirty.

So, when the fields are null or empty and the fields have been touched by the user and then our validations will start triggering and it will start showing the corresponding messages respectively.

There are a number of validation states which are available that we can use to provide the CSS classes correspondingly.

Also, we can make the submit button disabled untill the form is completely valid. Here is the code for disabling the submit button,

<button class="btn btn-primary" type="Submit" [disabled]="!simpleForm.valid">Submit</button>

Comments