Explore Angular 4 Form Validation With Example – For Beginners

This article will guide you to over Angular 4 form validation with example on both model and reactive forms approach.

Angular 4 Form Validation With Example

As we’ve already gone through on Forms tutorial, there’re two kinds of forms approach in Angular 4. One is template driven and another is reactive forms approach.

Template-driven, as name suggested, it’s completely dependent on the HTML part and there’s no dependency on the component or model.

Where as, Reactive approach (Model-driven), is completely dependent on the component and it passes the validations to the HTML. Let’s see how they both works.

First of all, we’ll create a template-driven form and then we’ll go for reactive approach.

1. Angular 4 Template driven forms validation

For template driven forms validation, you can use all the methods which we can use for native HTML forms.

Whenever the value of form control changes, Angular runs validations and results in a state of validations, i.e. either INVALID or VALID.

Let’s take an example.

This following element will have the validation required, minLength and forbiddenName.

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

So, whenever you’d like to show a message for a particular element, you can use methods like invalid, dirty and touched.

<div *ngIf="name.invalid && (name.dirty || name.touched)" class="alert alert-danger">
<!-- Required validation -->
<div *ngIf="name.errors.required">
   Name is required.
</div>
<!-- minLength validation -->
<div *ngIf="name.errors.minlength">
   Name must be at least 4 characters long.
</div>
<!-- forbiddenName validation -->
<div *ngIf="name.errors.forbiddenName">
   Name cannot be Bob.
</div>
</div>

Takeaways,

  • As mentioned, you can apply native HTML validation methods like required, minLength, etc.
  • #name=”ngModel”, will exports NgModel into a local variable called name. This way you can find the state is valid or dirty.
  • Finally, to show the respective validation methods, you can use ngIf directive with form control and it’s validation methods.

2. Angular 4 Reactive forms validation

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

Let’s define a simple form and it’s validations

app.component.ts

//Import core modules
import { Component, OnInit } from '@angular/core';
//Import forms modules
import { FormControl, FormGroup, Validators } from '@angular/forms';

//Component decorator
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
//App component class
export class AppComponent implements OnInit {
  title = 'Angular 4 Reactive Forms';
  simpleForm: FormGroup;

  ngOnInit() {
  	this.simpleForm = new FormGroup({
  		'name': new FormControl(null, Validators.required),
  		'desc': new FormControl(null, Validators.required),
  	});
  }

  saveData(){
	//Save data code
  }
}

Takeaways,

  • First part, importing the necessary module into the component.
  • The middle part has the @Component decorator.
  • In the last part, class has defined the simpleForm as a FormGroup with number of members i.e. FormControl.

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

Now, let’s see how we can implement the actual HTML form in the template.

app.component.html

Here, we’ll defined a simple HTML form with the FormGroup and FormControl.

<form [formGroup]="simpleForm" (ngSubmit)="saveData()">
<!-- Name field -->
<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 name.</p>
  </div>
</div>
<!-- Desc field -->
<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 desc.</p>
  </div>
</div>
</form>

Takeaways,

  • Firstly, we’ve defined the form with formGroup named as simpleForm that we’ve actually defined in the component.
  • Secondly, we’ve two form controls as formControlName which we’ve also we’ve defined in our component as FormControl.
  • Third is we can show the validations by using the default methods like valid and touched.

So, when the fields are empty and fields been touched by the user then these validations will be triggered and will show the defined messaged respectively.

There’re number of validation states available that you can use to provide the CSS classes.

Also, you can make the submit button disabled till your form is fully valid.

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

Suggested visit: Build your first form using Reactive Forms

I hope, you now have an idea of using Angular 4 form validation with example for both the approaches.

Mohit Tanwani

Mohit Tanwani is an enthusiast Techie, a blogger, and IT geek. He has been crazily involved in the industry for 5 years.

Leave a Reply

Be the First to Comment!

avatar
  Subscribe  
Notify of