In this tutorial, you will learn, how to validate the input fields of the Ionic 2 framework application using the Angular2 library.

Browser Preview of Form Validation(Android, iOS, and Windows).

Angular2 offers built-in Validators class to validate the input fields. The Validators class contains some built-in method for validation. They are listed below.

static min(min: number): ValidatorFn

Validator that requires controls to have a value greater than a number.

static max(max: number): ValidatorFn
Validator that requires controls to have a value less than a number.

static requiredTrue(control: AbstractControl): ValidationErrors|null
Validator that requires control value to be true.

static required(control: AbstractControl): ValidationErrors|null
Validator that requires controls to have a non-empty value.

static email(control: AbstractControl): ValidationErrors|null
Validator that performs email validation.

static minLength(minLength: number): ValidatorFn
Validator that requires controls to have a value of a minimum length.

static maxLength(maxLength: number): ValidatorFn
Validator that requires controls to have a value of a maximum length.

static pattern(pattern: string|RegExp): ValidatorFn
Validator that requires a control to match a regex to its value

For more information about the Validator class use the below link.

https://angular.io/api/forms/Validators

In this tutorial, I will explain how to use the built-in validation function. However, this is not sufficient to validate all input fields. In the next tutorial, I will explain how to write the custom validation function.

https://ampersandacademy.com/tutorials/ionic-framework-version-2/how-to-write-the-custom-validation-function

The Validator class can be used in the FormControl class. FormControl points the particular input field. You can define multiple Validators for the form control. All the FormControl element are grouped using the FormGroup. So the hierarchy is listed below.

1. FormGroup
2. FormControl
3. Validators

Create a new Ionic 2 project using the below command.

ionic start app blank --v2

Import the FormControl, FormGroup, Validators class to the home.ts file.

import { FormControl, FormGroup, Validators,ValidatorFn,AbstractControl } from '@angular/forms';

Import the OnInit class, which is used to call the form validation asynchronously.

import { OnInit } from '@angular/core';

Implement OnInit with HomePage class.

export class HomePage implements OnInit {
}

Create a form group variable.

user: FormGroup;

Assume you have three input fields such as name, email and mobile number. Now we are going to create form control for each input field. And add the validation for each form control.

Create a simple validation for the name input field using the below code.

name: new FormControl('', [Validators.required, Validators.minLength(4)])

The name input field had two validation.
1. You can leave this as empty.
2. Minimum 4 characters are required

Now write a function to implement the validation for the three input fields.

ngOnInit() {

this.user = new FormGroup({
name: new FormControl('', [Validators.required, Validators.minLength(4)]),
email: new FormControl('', [Validators.required,Validators.email]),
mob: new FormControl('', [Validators.required, Validators.minLength(10),Validators.maxLength(10)])
});

}

The ngOnInit function will be called once the HomePage loaded fully.

The email had two validation. They are.
1. You can leave the email field as empty
2. You must enter the valid email id

The mobile number had three validation. They are.
1. You can leave the mobile field as empty
2. The minimum length must be ten
3. The maximum length must be ten

The home.ts file work is over. Now we need to create the input field in the home.html file.

Create a form in the home.html file and mark the form group name to be user.

<form novalidate (ngSubmit)="onSubmit(user)" [formGroup]="user">

</form>

Now create a name input field inside the form tag.

<ion-item>
<ion-label >Username</ion-label>
<ion-input type="text" value="" formControlName="name"></ion-input>

</ion-item>

You have to use the same form control name here which is used in the home.ts file. Now we need to add the validation message here. You can check whether the input field is validated or not using the below syntax.

formGroupVariable.get('formControlName').hasError('ValidationName')

Example:

user.get('name').hasError('minlength')

The name had required and minlength validation. So we can write like below.

<div class="error" *ngIf="user.get('name').hasError('required') && user.get('name').touched">
Name is required
</div>
<div class="error" *ngIf="user.get('name').hasError('minlength') && user.get('name').touched">
Minimum of 4 characters
</div>

The user.get('name').touched will be triggered whenever the user clicks the input field.

Now add the corresponding validation to the other input fields too. That's all. You are done.

You can preview this application using the browser. Use the below command for live preview.

cd app
ionic serve --lab

Below are the Ionic 2 software information while writing this tutorial.

Cordova CLI: 6.5.0 
Ionic Framework Version: 3.6.0
Ionic CLI Version: 2.2.1
Ionic App Lib Version: 2.2.0
Ionic App Scripts Version: 2.1.3
ios-deploy version: Not installed
ios-sim version: 5.0.13 
OS: macOS Sierra
Node Version: v6.10.0
Xcode version: Xcode 8.2.1

Home.html source code.

<ion-header>
<ion-navbar>
<ion-title>
Ionic Blank
</ion-title>
</ion-navbar>
</ion-header>

<ion-content padding>


<form novalidate (ngSubmit)="onSubmit(user)" [formGroup]="user">

<ion-item>
<ion-label >Username</ion-label>
<ion-input type="text" value="" formControlName="name"></ion-input>

</ion-item>

<ion-item no-lines *ngIf="( user.get('name').hasError('minlength') || user.get('name').hasError('required') ) && user.get('name').touched">

<div class="error" *ngIf="user.get('name').hasError('required') && user.get('name').touched">
Name is required
</div>
<div class="error" *ngIf="user.get('name').hasError('minlength') && user.get('name').touched">
Minimum of 4 characters
</div>
</ion-item>






<ion-item>
<ion-label >Email</ion-label>
<ion-input type="text" value="" formControlName="email"></ion-input>


</ion-item>

<ion-item no-lines *ngIf="( user.get('email').hasError('required') || user.get('email').hasError('email') ) && user.get('email').touched">



<div class="error" *ngIf="user.get('email').hasError('required') && user.get('email').touched">
email is required
</div>

<div class="error" *ngIf="user.get('email').hasError('email') && user.get('email').touched">
Please enter valid email
</div>

</ion-item>



<ion-item>
<ion-label >Mob</ion-label>
<ion-input type="text" value="" formControlName="mob"></ion-input>


</ion-item>

<ion-item no-lines *ngIf="( user.get('mob').hasError('required') || user.get('mob').hasError('minlength') || user.get('mob').hasError('maxlength'))&& user.get('mob').touched">



<div class="error" *ngIf="user.get('mob').hasError('required') && user.get('email').touched">
mobile no is required
</div>
<div class="error" *ngIf="user.get('mob').hasError('minlength') && user.get('email').touched">
Please enter valid mobile number
</div>

<div class="error" *ngIf="user.get('mob').hasError('maxlength') && user.get('email').touched">
Please enter valid mobile number
</div>


</ion-item>




<button ion-button [disabled]="user.invalid">Sign up</button>
</form>

</ion-content>


<style type="text/css">
.error
{
color:red;
}

</style>

 

Home.ts file source code.
 

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {  OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators,ValidatorFn,AbstractControl } from '@angular/forms';

@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage implements OnInit {

user: FormGroup;

constructor() {

}
ngOnInit() {

this.user = new FormGroup({
name: new FormControl('', [Validators.required, Validators.minLength(4)]),
email: new FormControl('', [Validators.required,Validators.email]),
mob: new FormControl('', [Validators.required, Validators.minLength(10),Validators.maxLength(10)])
});

}




}