Ionic Form Validation

In this section, we will learn complex form validation through ngForm and ngControl. We will create service file (MyFormService) where we define our form class. This class will have all the form field. Validation applied to the following field.

  1. The name field is required.
  2. Validate comment field is required and the user must enter a minimum of four characters.
  3. The user must agree to the terms and conditions via toggle input.

Once all above conditions are made and user click on submit button. We will send all the input field of the form to display on the second page.

To achieve our form validation apps, we need to follow certain step
Step 1: ionic start MyFormValidation blank –v2
Step 2: mkdir ./src/services
Create a myform.ts, add the following code to define MyformService class. We need to add MyFormService as provider in app.module.ts as providers: [MyFormService]

import { Injectable } from '@angular/core';
@Injectable()
export class MyFormService {
    public name: string = '';
    public phone: number;
    public comment: string = '';
 
    constructor(){}
}

 

Step 3: We need to add form in our home.hmtl. We have temporary local Boolean variable isSubmitted, we will use this variable to check whether the form is submitted or not.

<ion-header>
  <ion-navbar>
    <ion-title> Contact From</ion-title>
  </ion-navbar>
</ion-header>
 
<ion-content>
<p class="center">
  <ion-icon class="large lighter" primary name="contact"></ion-icon>
</p>
<form #f="ngForm" novalidate (ngSubmit)="onSubmit(f)">
  <ion-list>
 
    <ion-item>
        <ion-label floating>Name</ion-label>
        <ion-input type="text" name="name" required [(ngModel)]="data.name"></ion-input>
    </ion-item>
 
    <div [hidden]="f.controls.name && (f.controls.name.valid || (f.controls.name.pristine && !isSubmitted))" class="note danger">
      Name is required
    </div>
 
    <ion-item>
      <ion-label floating>Phone</ion-label>
      <ion-input type="tel" name="phone" [(ngModel)]="data.phone"></ion-input>
    </ion-item>
 
    <ion-item>
      <ion-label floating>Comment</ion-label>
      <ion-input type="text" required minlength=4 name="comment" [(ngModel)]="data.comment"></ion-input>
    </ion-item>
 
    <div *ngIf="(isSubmitted && f.controls.comment && f.controls.comment.pristine) || ((f.controls.comment) && 
      (f.controls.comment.dirty && f.controls.comment.errors))" class="note danger">
      Please enter {{ 4 - (f.controls.comment.errors.minlength ? f.controls.comment.errors.minlength.actualLength : 0)  }} more characters    
    </div>
 
 
    <ion-item class="tos">
      <ion-toggle item=left [(ngModel)]="data.tos" name="tos" type="button" (click)="noSubmit($event)"></ion-toggle>
      <ion-label item-right>Agree to terms and conditions</ion-label>
    </ion-item >
 
 
    <div [hidden]="(!isSubmitted) || (f.controls.tos && data.tos)" class="note danger">
      Please check Agree1
    </div>
 
    </ion-list>
 
    <div class="center">
      <button ion-button type="submit" round outline>Submit</button>
    </div>
  </form>
</ion-content>

 

In our home.html # is used to make local variable.#f variable refers to ngForm which is automatically created by angular. This is a special object that contains all information related to current form. The (ngSubmit) an event will trigger the onSubmit(f) method whenever the user clicks on submit button of our form.

Step 4: We need to add following code in home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { ThankyouPage } from '../thankyou/thankyou';
import { MyFormService } from '../../services/myform'
 
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  private data: any;
  private isSubmitted: Boolean = false;
 
  constructor(public nav: NavController, private formData: MyFormService) {
    this.nav = nav;
    this.formData = formData;
    this.data = {
      name: '',
      phone:'',
      comment:'',
      tos:false
    }
  }
  onSubmit(myForm) {
    this.isSubmitted = true;
    console.log('onSubmit');
    console.log(myForm);
 
    if((myForm.valid) && (myForm.value.tos)) {
      this.formData.name = this.data.name;
      this.formData.phone = this.data.phone;
      this.formData.comment = this.data.comment;
      this.nav.push(ThankyouPage);
    }
  }
  noSubmit(e){
    e.preventDefault();
  }
}

We will add style to our home.scss

.center{
    text-align: center;
}
 
ion-icon.large {
    font-size: 7em;
}
 
ion-icon.lighter{
    opacity: 0.5;
}
 
ion-list > .item:first-child{
    border-top:0;
}
 
ion-list > .item:last-child, ion-list > ion-item-sliding:last-child .item{
    border-bottom:0;
}
 
.tos{
    padding-top:10px;
 
    ion-toggle{
        padding-left: 0px;
    }
    .item-inner {
        border-bottom: 0;
    }
 
    .item-inner{
        border-bottom:0;
    }
}
.item ion-toggle{
    padding-left: 0;
}
 
.note.danger {
    padding-left:16px;
    color:#d14;
}

 

Step 5: We will create thankyou page, This page will accept and display the input field of our form of home.html.
>>ionic g page thankyou.
Add following code in our thankyou.ts

import { Component } from '@angular/core';
import { MyFormService } from '../../services/myform';
 
@Component({
    templateUrl: 'thankyou.html'
})
 
export class ThankyouPage{
    constructor(private formData: MyFormService){
        this.formData = formData;
    }
}

Add the following code in home.html

<ion-header>
    <ion-nav color="secondary">
        <ion-title>Thank You</ion-title>
    </ion-nav>
</ion-header>
 
<ion-content>
    <h6 class="padding">You submitted the following information</h6>
    <div class="my-table">
        <ion-row>
            <ion-col width-25 class="my-label">Name</ion-col>
            <ion-col width-75>{{ formData.name }}</ion-col>
        </ion-row>
        <ion-row>
            <ion-col width-25 class="my-label">Phone</ion-col>
            <ion-col width-75>{{ formData.phone }}</ion-col>
        </ion-row>
        <ion-row>
            <ion-col width-25 class="my-label">Comment</ion-col>
            <ion-col width-75>{{ formData.comment }}</ion-col>
        </ion-row>
    </div>
</ion-content>