In this tutorial, you will learn, how to write the custom validation function using the Angular2 in the Ionic2 mobile applications.

The Angular2 offers us a validation class, which is Validators. The Validators class does not contain all the required validation function. Even it is missing the number validation too. The below are the built-in validation function in the Validators class.

class Validators {
static min(min: number): ValidatorFn
static max(max: number): ValidatorFn
static required(control: AbstractControl): ValidationErrors|null
static requiredTrue(control: AbstractControl): ValidationErrors|null
static email(control: AbstractControl): ValidationErrors|null
static minLength(minLength: number): ValidatorFn
static maxLength(maxLength: number): ValidatorFn
static pattern(pattern: string|RegExp): ValidatorFn
static nullValidator(c: AbstractControl): ValidationErrors|null
static compose(validators: (ValidatorFn|null|undefined)[]|null): ValidatorFn|null
static composeAsync(validators: (AsyncValidatorFn|null)[]): AsyncValidatorFn|null
}

If you want to learn the Validators class with some built-in validation function, then use the below link.

https://ampersandacademy.com/tutorials/ionic-framework-version-2/form-validation-with-error-message-example-using-the-angular-validators

So in this tutorial, I am going to explain you, how to write the custom validation function by yourself and how to integrate the custom validation function to the form control.

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

Here we will see two custom validation function. They are
1. Number validation.
2. URL validation

Number Validation Function.

Create a new Ionic 2 project using the below command.

ionic start app blank --v2

Import the Validation related classes. The most important class to write the custom validation is ValidatorFn.

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

Now create a simple function.

number_check()
{
}

Then mark this function as validation function by mentioning the return type to ValidatorFn.

number_check(): ValidatorFn { }

Now add the AbstractControl class, which is used to get the input values. Use the AbstractControl class with the return statement.

number_check(): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} => {

};
}

Get the input value using the AbstractControl.

let input = control.value;

Now create a simple JavaScript Regular Expression object, with the number check pattern.

var re = new RegExp("^(\\d+)$");

Now test the input value with regular expression pattern.

let isValid=re.test(input);

If the pattern matches, then there is no error. So return null. If the pattern is not matching, then return the error key with a boolean value.

number_check(): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} => {
var re = new RegExp("^(\\d+)$");
let input = control.value;
let isValid=re.test(input);
if(!isValid)
return { 'number_check': {isValid} }
else
return null;
};
}

The error key is used to check and display the error message to this custom validation function.

The custom validation function is ready. Create a form control to include this custom validation function.

Now import the OnInit to the home.ts file.

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

Then implement the OnInit with the HomePage class.

export class HomePage implements OnInit { }

Create the ngOnInit function and create form group and form control like below.

ngOnInit() {

this.user = new FormGroup({
mobile: new FormControl('', [])
});

}


Now add the number_check function to the form control validator.

ngOnInit() {

this.user = new FormGroup({
mobile: new FormControl('', [Validators.required, this.number_check()])
});

}

The Angular2 part is over for the custom validation function. Now create a form with the input field in the home.html file.

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

<ion-item>
<ion-label >Mobile No</ion-label>
<ion-input type="text" value="" formControlName="mobile"></ion-input>

</ion-item>
</form>

Now add the error message here.

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

<div class="error" *ngIf="user.get('mobile').hasError('required') && user.get('mobile').touched">
Mobile No is required
</div>
<div class="error" *ngIf="user.get('mobile').hasError('number_check') && user.get('mobile').touched">
Please enter only number(s).
</div>
</ion-item>

Use the below command to run this application.

cd app
ionic serve --lab

URL Validation Function.

Use the below code in the home.ts file for URL validation.

URL_check(): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} => {
var re = new RegExp("^(http[s]?:\\/\\/(www\\.)?|ftp:\\/\\/(www\\.)?|www\\.){1}([0-9A-Za-z-\\.@:%_\+~#=]+)+((\\.[a-zA-Z]{2,3})+)(/(.)*)?(\\?(.)*)?");
let input = control.value;
let isValid=re.test(input);
if(!isValid) 
return { 'url_check': {isValid} }
else 
return null;
};
}

Add the below code in the home.html file.

<ion-item>
<ion-label >URL</ion-label>
<ion-input type="text" value="" formControlName="url"></ion-input>

</ion-item>

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

<div class="error" *ngIf="user.get('url').hasError('required') && user.get('url').touched">
The URL is required
</div>
<div class="error" *ngIf="user.get('url').hasError('url_check') && user.get('url').touched">
Please enter valid URL.
</div>
</ion-item>

Below is 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 >Mobile No</ion-label>
<ion-input type="text" value="" formControlName="mobile"></ion-input>

</ion-item>

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

<div class="error" *ngIf="user.get('mobile').hasError('required') && user.get('mobile').touched">
Mobile No is required
</div>
<div class="error" *ngIf="user.get('mobile').hasError('number_check') && user.get('mobile').touched">
Please enter only number(s).
</div>
</ion-item>


<ion-item>
<ion-label >URL</ion-label>
<ion-input type="text" value="" formControlName="url"></ion-input>

</ion-item>

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

<div class="error" *ngIf="user.get('url').hasError('required') && user.get('url').touched">
The URL is required
</div>
<div class="error" *ngIf="user.get('url').hasError('url_check') && user.get('url').touched">
Please enter valid URL.
</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 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({
mobile: new FormControl('', [Validators.required, this.number_check()]),
url: new FormControl('', [Validators.required, this.URL_check() ] )
});

}


number_check(): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} => {
var re = new RegExp("^(\\d+)$");
let input = control.value;
let isValid=re.test(input);
if(!isValid) 
return { 'number_check': {isValid} }
else 
return null;
};
}

URL_check(): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} => {
var re = new RegExp("^(http[s]?:\\/\\/(www\\.)?|ftp:\\/\\/(www\\.)?|www\\.){1}([0-9A-Za-z-\\.@:%_\+~#=]+)+((\\.[a-zA-Z]{2,3})+)(/(.)*)?(\\?(.)*)?");
let input = control.value;
let isValid=re.test(input);
if(!isValid) 
return { 'url_check': {isValid} }
else 
return null;
};
}


}