Friday, 17 November 2017

How to Implement Form Validations in Ionic 2 and 3

We generally implement input fields with [(ngModel)] which uses two way data binding between template and variable, so that what you type or enter in the input field gets binded to variable that is accessible in the .ts file. for example if you have an input field like below:


<ion-input type="text" [(ngModel)]="myInput"></ion-input>


the value you entered in the above input gets binded to this.myInput which can be accesses from respective class definition.
Although the above procedure is fair to use, but if you want to implement validations, it can be somewhat time consuming.
So, to overcome this in this tutorial we are going to learn, how to implement complex form validations ionic 2/3 applications.
Note: if you want to check out the code or you only want the code, you can download the component here, after downloading just copy and paste the component in to your projects src/pages folder that's it.
Now lets get to implemeting form validatons in ionic framework,

We will be using FormGroup & FormControl in this tutorial to create and validate form's in ionic 2/3.
This tutorial assumes that you already have the project created in ionic 2/3.

Copy & Paste the below code to your Components html page


<ion-header>
  
    <ion-navbar>

	    <button ion-button menuToggle>
          <ion-icon name="menu"></ion-icon>
        </button>
      <ion-title>Form Validation</ion-title>

    </ion-navbar>
  
</ion-header>

<ion-content>
  
<ion-list no-lines>
      <p style="padding: 15px;"><b>Title:</b> A tutorial to demonstrate Form Validations in ionic 2/3.</p>
	  
      <form [formGroup]="signUp" (ngSubmit)="SignUpForm()">

        <ion-item class="itemStyle">
          <ion-label>Name</ion-label>
          <ion-input type="text" formControlName="name" clearInput [class.invalid]="!signUp.controls.name.valid && signUp.controls.name.dirty"></ion-input>
        </ion-item>

        <ion-item class="itemStyle">
          <ion-label>Email</ion-label>
          <ion-input type="email" formControlName="email" clearInput [class.invalid]="!signUp.controls.email.valid && signUp.controls.email.dirty"></ion-input>
        </ion-item>

        <ion-item class="itemStyle">
          <ion-label>Contact Number</ion-label>
          <ion-input type="number" formControlName="contactnumber" clearInput [class.invalid]="!signUp.controls.contactnumber.valid && signUp.controls.contactnumber.dirty"></ion-input>
        </ion-item>

        <ion-item class="itemStyle">
          <ion-label>Password</ion-label>
          <ion-input type="password" formControlName="password" clearInput [class.invalid]="!signUp.controls.password.valid && signUp.controls.password.dirty"></ion-input>
        </ion-item>

        <button ion-button block type="submit" [disabled]="!signUp.valid" style="background-color: #343434;width: 90%;margin: auto;color:white;font-weight: 600;margin-top:20px;">Sign Up</button>
      
      </form>
</ion-list>

</ion-content>



Here, we have a formGroup property with a value of signUp which we are going to create the form with. if not, You might have already observed that we dont have [(ngModel)] here because its work is carried out by formControlName here. every input here has an formControlName which are used to carry and validate input values.
[class.invalid] is applied if the particular formControlName is invalid or dirty. [disabled]="!signUp.valid" disables submit button until the form is valid.
Copy & Paste the ts code to your Components .ts file.


import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams} from 'ionic-angular';
import {Validators, FormBuilder, FormGroup } from '@angular/forms';

/**
 * Generated class for the FormcontrolPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-formcontrol',
  templateUrl: 'formcontrol.html',
})
export class FormcontrolPage {

  private signUp : FormGroup;

  constructor(public navCtrl: NavController, public navParams: NavParams, private formBuilder: FormBuilder) {
    
    let EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
    
    this.signUp = this.formBuilder.group({

            name: ['', Validators.compose([Validators.maxLength(30), Validators.pattern('[a-zA-Z ]*'), Validators.required])],
            password: ['', Validators.compose([Validators.maxLength(10), Validators.required])],
            email: ['', Validators.compose([Validators.required, Validators.pattern(EMAIL_REGEXP)])],
            contactnumber: ['', Validators.compose([Validators.maxLength(10), Validators.required])],
    
    });
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad FormcontrolPage');
  }
  
  SignUpForm(){
	  console.log(this.signUp.value)
  }

}


dont forget to include this in you .scss file.

Copy and Paste the Below css code to you components .scss file.


    .itemStyle{
        margin-bottom: 15px !important;
        width: 90%;
        margin: auto;
        border-radius: 8px;
        background-color: #eaeaea;
    }  

    .invalid {
		border: 1px solid #f90000;
		border-radius: 5px;
    }


Now that you have all the code in place, lets get to the explanation part, shall we.
Here we are importing Validators, FormBuilder, FormGroup into our page/component from @angular/forms. FormBuilder will be used to create FormGroup which have all the FormControls, which intern have all the values that you entered into the form.
Create a member variable signUp of type FormGroup. Now can use this signUp member variable to create our form.The formBuilder.group function is used to create our FormGroup by supplying an object containing each of our FormControls(ie. formControlName).
Validators.compose function is used to set multiple validators. default validators that are commonly used for validation are,
.Validators.required
.Validators.minLength
.Validators.maxLength
.Validators.pattern


The required validator requires that the value is not empty, minLength and maxLength ensure that the length of the input is of a certain length, and where as pattern uses a regex pattern to validate the form input.

0 comments:

Post a Comment