FORM VALIDATION IN IONIC 3

Share the post

Today, We will see How to do form validation in ionic 3 & Angular 5? How to use form tag in HTML and How to validate it using Form, Validators. Follow the below steps. We are going to import Validators, FormBuilder, FormGroup & FormControl from @angular/forms package.

1.Genereate a new page by using the command :

ionic g page form-example

you can see here what are the different types of commands used to Generate ionic pages, components & pipes.

2.Import the module in app.module.ts :

import { FormExamplePage } from '../pages/form-example/form-example';



@NgModule({
  declarations: [
    FormExamplePage
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    IonicModule.forRoot(MyApp),
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    FormExamplePage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    LocalNotifications,
    Geolocation,
    InAppBrowser,
    SocialSharing,
    { provide: ErrorHandler, useClass: IonicErrorHandler },
    RestProvider,
    CommonProvider,
    QRScanner
  ]
})
export class AppModule { }

3.Update app.component.ts (Optional just to show side menu option for form validation example) :

import { Component, ViewChild } from '@angular/core';
import { Nav, Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

import { FormExamplePage } from '../pages/form-example/form-example';




@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  @ViewChild(Nav) nav: Nav;


  rootPage: any = LoginPage;


  pages: Array<{ title: string, component: any }>;


  constructor(public platform: Platform, public statusBar: StatusBar, public splashScreen: SplashScreen) {
    this.initializeApp();


    // used for an example of ngFor and navigation
    this.pages = [
      { title: 'Home', component: HomePage },
      { title: 'Tabs', component: TabsPage },
      { title: 'Form Validation', component: FormExamplePage }

    ];
  }


  initializeApp() {
    this.platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      this.statusBar.styleDefault();
      this.splashScreen.hide();
    });

  }


  openPage(page) {
    // Reset the content nav to have just this page
    // we wouldn't want the back button to show in this scenario
    this.nav.setRoot(page.component);
  }
}

4.Write form-example.html (Write form tag)

<!--
  Generated template for the FormExamplePage page.


  See http://ionicframework.com/docs/components/#navigation for more info on
  Ionic pages and navigation.
-->
<ion-header>
  <ion-navbar>
    <ion-title>Form Example</ion-title>
  </ion-navbar>
</ion-header>


<ion-content padding>
  <form [formGroup]="exampleForm">


    <ion-item>
      <ion-label>Email Id</ion-label>
      <ion-input type="text" formControlName="email" [ngModel]="email" placeholder="Enter email here">
      </ion-input>
    </ion-item>


    <ion-row *ngIf="exampleForm.controls.email.invalid && exampleForm.controls.email.dirty">
      <ion-col>
        <span class="error-txt">Please enter a valid email</span>
      </ion-col>
    </ion-row>


    <ion-item>
      <ion-label>Password</ion-label>
      <ion-input type="password" formControlName="password" [ngModel]="password" placeholder="Enter password here">
      </ion-input>
    </ion-item>


    <ion-row *ngIf="exampleForm.controls.password.invalid && exampleForm.controls.password.dirty">
      <ion-col>
        <span class="error-txt">Please enter a valid password</span>
      </ion-col>
    </ion-row>


    <ion-item>
      <button ion-button color="primary" block [disabled]="exampleForm.invalid" (click)="submit()">Sign In</button>
    </ion-item>


    <ion-item>
      <button ion-button color="primary" block (click)="checkForm()">Check Form</button>
    </ion-item>
  </form>


</ion-content>


Under the form tag, we need to add the FormGroup name. Under FormGroup name we need to add a form control name for each input type.

5.Write form-example.ts as follows :

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

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

@IonicPage()
@Component({
  selector: 'page-form-example',
  templateUrl: 'form-example.html',
})
export class FormExamplePage {

  exampleForm: FormGroup;
  email: string = '';
  password: string = '';

  constructor(public navCtrl: NavController, public navParams: NavParams, public formBuilder: FormBuilder) {

    this.exampleForm = new FormGroup({
      'email': new FormControl('', [Validators.required, Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')]),
      'password': new FormControl('', [Validators.required, Validators.pattern('^[a-zA-Z0-9_.+-]+$')]),
    })
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad FormExamplePage');
  }

  submit() {
    console.log("Validate successfully");
  }

  checkForm() {
    console.log(this.exampleForm);
  }

}

In this ts file after importing the necessary modules we need to add the FormGroup name which used in the HTML page.
In constructor Under the form, the group needs to add all form control names that want to control by using different Validators.

Here are some Validators that can be used:

Validators.required: For Required Fields
Validators.pattern: To implement different angular regex patterns like for email we have used the above pattern
Validators.min: For minimum length, want’s to display for input fields
Validators.max: For maximum length, want’s to display for input fields

6.Write form-example.css:

page-form-example {
.error-txt{
    color :red;
    font-size: 12px;
    }
}

The output of the above example looks as follows : 

Form_Validation_Ionic3_Angular5
Output

So, FormGroup contains a form control name. It controls all the validation required for the field. Suppose if you have a large HTML file then you can use multiple FormControl inside a single FormGroup. So, that you have better control over the validation of every input field.

If the form is invalid you cannot able to submit the form & if you want to check every Form control status individually then you have to press the check form button.

Leave a Comment