The original version of this article was written two years ago, which is way too old for what Ionic can provide today. I never intended to update this article, why spend so much time managing old content when Ionic/Angular are changing so fast, sometimes not even in a good way. To some point, I’m regretting that decision; not completely but enough that it’s bothering me on a daily basis. So, in that light let me introduce you the next iteration of this article. Hopefully, it will serve you better than the old one.
 
In my previous (it was so long ago) article, I demonstrated how to share data between different Ionic [2|3] pages or components. This specific tutorial will show you how we can work and build application forms including data validations.
 
Subjectively, I can’t remember anything in Ionic 1 as annoying as form handling and validations. This is mostly due to Angular shortcomings; I don’t want to use this comment as a hit on Ionic 1.
 
In those dark ages, we had to use ngModel to map our form data model. Thankfully, now we’re doing it much more explicitly; we’re probably going to use more code than before, but, at the same time, it will be much easier to understand. One last thing, don’t forget, we no longer need to play with frustrating ngModel and suffer any scope data problems.
 
The advent of Angular 2 has brought us a quite bit different way of form handling, especially compared to what we had with Angular 1. I will show you how to translate these changes to Ionic 2 application, but, at the same time, you can count this as Angular 2|4 article.
 
 

Note: If this tutorial was helpful, need further clarification, something is not working or do you have a request for another Ionic post? Furthermore, if you don't like something about this blog, if something is bugging you, don't like how I'm doing stuff here, again leave me a comment below. I'm here to help you, I expect the same from you. Feel free to comment below, subscribe to my blog, mail me to dragan.gaic@gmail.com, or follow and mention me on twitter (@gajotres). Thanks and have a nice day!

PS. If you want my help, if possible (even if it takes you some time to do that), create a working example I can play with. Use Plunker for AngularJS based questions or jsFiddle for jQuery/jQuery Mobile based questions.


 

Table of Contents

 
Is Ionic (2 or 3) causing you problems? Are you struggling with your application? Trust me, I was in the same situation like you. If you require more information beyond the subject of this article, you will probably find it in a list below. Take a look; if there’s a topic not covered here, leave me a comment, and I will do my best to cover it.
 
 

Preparations

 
As always, make sure you have everything set up for Ionic [2|3] development. One last thing, as this framework is now known only as Ionic, further down the line I will refer to it as such; I will not use any version numbers. I will simply refer to it as Ionic.
 
To continue working on this tutorial you should have these:
 
  • Android Environment (or iOS if you’re working on a MacOS)
  • nodeJS
  • Ionic
  • Cordova
 
If you don’t have a prior Ionic installation find more information here: Ionic [2|3] | Installation Guide.
 

1. Update Ionic CLI

 
If possible you should have the latest nodeJS version, without it, you’ll not be able to appropriately install/update Cordova and Ionic. Worst case scenario, use any recent version possible.
 
On the other hand, If you have already worked with Ionic/Cordova, make sure they’re up to date; older versions may not work with this tutorial:
 
npm install -g ionic cordova
 
or to do a simple update:
 
npm update -g ionic cordova
 
 

2. Create A New Project

 
ionic start IonicFormValidation blank
cd IonicFormValidation 
 
If you prefer a working example you will find it at the end of this article; if not, keep reading.
 
Warning: As some of you don't have a prior Ionic CLI experience, from this point and on, every time I tell you to execute something, do that inside an example project folder.
 

3. Add Required Platform

 
Add Android platform:
 
ionic cordova platform add android
 
MacOS users can also add iOS platform:
 
ionic cordova platform add ios
 

Embeded Example

 
Ionic 2 Form Validation
 

Source Walkthrough

 
I will make this tutorial as easy as possible; if you want to see a different example or case just leave me a comment. For now, our example will need only two pages. One page will cover authentication form while another one will hold a simple home page where we will end up after successful authentification.
 
Ionic blank app, as by default, comes with the pre-existing Homepage; we will need to add the second authorization page:
 
ionic generate page auth
 
This will generate a new folder called auth (inside pages folder) including our new AuthPage page. This process is done automatically, an AuthPage name was formed using page name we provided with ionic generate. You can also do this manually but this way is much faster and error free.
 
Just be careful, unlike Angular CLI generate, Ionic CLI generate will not integrate new page with rest of the code, we will need to do that manually.
 
So, as previously mentioned, before we can proceed any further, let’s include auth page into app.module.ts file.:
 
import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { AuthPage } from '../pages/auth/auth';

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    AuthPage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    AuthPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}
 
At this point, we have a simple app with two distinct pages. Let us proceed to app.component.ts file.
 
As we are offering authentication we first need to decide which page will show first. We will display auth page if an application was started for the first time, if authentication was unsuccessful or if logout function was triggered on the home page. On the other side, we will display homepage if authentication was successful, or if the original authentication was successful and login data was stored in a localstorage:
 
  checkPreviousAuthorization(): void { 
    if((window.localStorage.getItem('username') === "undefined" || window.localStorage.getItem('username') === null) && 
       (window.localStorage.getItem('password') === "undefined" || window.localStorage.getItem('password') === null)) {
      this.rootPage = AuthPage;
    } else {
      this.rootPage = HomePage;
    }
  }
 
Also, don’t forget to include AuthPage, as HomePage is the only one included by default:
 
import { AuthPage } from '../pages/auth/auth';
 
Now let’s open auth.ts page as we will spend most of our time there.
 
To be able to work with Ionic forms we need to import several Angular2 services, directives and objects:
 
import { FormBuilder, FormGroup, Validators, AbstractControl } from '@angular/forms';
 
  • While we can build forms using ngForm and ngControl, a more flexible way is using FormBuilder. It’s just a helper service (class) that helps us build forms using Control and ControlGroup objects.
  • A single Control object represents a single form item. At the same time, ControlGroup is a wrapper interface around a collection of Control objects.
  • Validators is a service (module) we use for validation purposes.
  • AbstractControl is an abstract class and a common ancestor of Control and ControlGroup.
 
For our example, we will use two distinctive input boxes and one submit button. For now, just disregard Angular2 syntax.
 
<ion-content padding>
    <form [formGroup]="authForm" (ngSubmit)="onSubmit(authForm.value)">
        <ion-item>
            <ion-label floating>Username</ion-label>
            <ion-input formControlName="username" type="text"></ion-input>
        </ion-item>
 
        <ion-item>
            <ion-label floating>Password</ion-label>
            <ion-input formControlName="password" type="password"></ion-input>
        </ion-item>

        <button ion-button full color="primary" [disabled]="!authForm.valid" style="margin-top: 20px;" type="submit">Authorize</button>        
    </form>
</ion-content>
 
Take a careful look at each input field, you’ll notice a special keyword called formControlName:
 
<ion-input formControlName="username" type="text"></ion-input>
 
This keyword defines a Control object (a single form field).
 
We will not need to manually change these values in our code but if you want to do that you can do it like this (in auth.ts):
 
username: AbstractControl;
password: AbstractControl;		
 
Both username and password are defined as AbstractControltype and they’re connected to HTML side using these lines:
 
this.username = this.authForm.controls['username'];	    
this.password = this.authForm.controls['password'];		
 
On the other hand, we will need to access our form directly:
 
<form [formGroup]="authForm" (ngSubmit)="onSubmit(authForm.value)">	
 
In auth.ts :
 
authForm: FormGroup;	
 
Continue to the next page

  • Works great 🙂 Thank you for sharing it. Though, I did not try custom method for validating.

    • You’re welcome … neighbour 🙂

    • karthiikk Baleneni

      whether its working in latest ionic2 beta v0.0.25

  • Thanks for that. It would be helpful to state what files these code blocks go into..

  • Thanks for that. This helped me a lot.

    I managed to get rid of the ‘function’ keyword in
    checkFirstCharacterValidator(control: Control): { [s: string]: boolean } { … }

    by adding ‘this’ in the Validators group:
    ‘username’: [”, Validators.compose([Validators.required, Validators.minLength(8), this.checkFirstCharacterValidator])],

    I also didn’t need to add the class declarations as they are already declared in the constructor:
    //authForm: ControlGroup;
    //username: AbstractControl;
    //password: AbstractControl;

    Lastly I changed the return line from the checkFirstCharacterValidator function to:
    return {“invalid_firstCharacter”: true};
    as I found naming the string and the method the same confusing (even though that’s what the native angular 2 validator functions do).

  • aluknot

    One of the things i don’t like about ionic 2 is the import part… you need to import a lot of things, when you only want to do something really simple. How can i remember this? i have to come back to this article every time.

  • Graciele E. Victor

    I’d love to see this article updated to Ionic 2 beta 6

  • karthiikk Baleneni

    whether it will work in Ioinic 2 @beta 0.25?? seems to be its not working.

  • Cyril Zilbermann

    Hi,
    Thanks for your share !
    I’m very newbie on ionic.
    However, I’ve a trouble : I’ve copy/paste your code for testing and I’ve compilation parsing error on three variables declaration (authForm, username and password).
    It seems does not accept variable declaration on class and I don’t know why.
    Could you help me ?
    Thanks

    • Cyril Zilbermann

      Sorry,
      My bad, i tried to work a TS code like a JS one :/
      Works perfectly !
      Thanks !

  • Varshil Shah

    hi i used your code AND ITS’S RUN PERFECT BUT PROBLEM IS THAT I WANT USERNAME AND PASSWORD IN STRING VARIABLE . I DON’T KNOW HOW I DO THAT

    • Don’t forget that this is still JavaScript and that every object is easily readable.

      For example, you can use this:

      console.log(this.username);

      To find out what AbstractControl object looks like. And it will tell you that value is accessible like this:

      console.log(this.username.value);
      console.log(this.password.value);

      • Varshil Shah

        thanx..solved problem

        • Your welcome

          • Varshil Shah

            Hey I have one another problem..I getting the response from the server now it’s not fully json response so I want cut string how I do it in ionic 2..

          • My advice, Google it

          • Varshil Shah

            i already do it but i didn’t anything find it.

  • Davide Troise

    HI! I’m trying to follow your guide, but there’s no way i can make the custom Validator Work :/
    I wrote a console.log() in the validator, but it never appears, like it’s never called! Would you please paste your whole CustomValidator.ts file? Thanks!

    • Just download my GitHub example, you can find it on the second page. Though I will also add CustomValidator.ts, I forgot to add it after my last article update.

      • Andre Dreyer

        After having a look at the required validator I realised that the logic of the custom validator function had to be inverted. If (valid) return null else return {‘required’: true}

    • I have update article with CustomValidators.ts class example

  • Palmani

    Hi, Thanks for your post. It’s really helped a lot. Please help me to add validation for creating dynamic elements. i’m trying to add validation for input elements using ng-repeat.

  • Áron Barócsi

    is this is depreciated as of rc4?

    • James Trigg

      Yes think so. beta11 is now using the new angular forms.
      think you use some setting in ionicBootstrap to use the old forms but not really the way forward.

  • james stevens

    hey i am not able to submit the form,when i click on submit there is no submitted values shown in the console

  • manoj meshram

    hi, There is any way to submit image with form’s other field?

  • Lokesh Sahu

    How to prevent hidden field validation. In my form i have a select box, if i select one option some fields are visible, if select another option then other fields are visible and the previous fields are hidden.

    • Andreza Pollyana

      Hi, maybe this kind of validator will help you

      ‘note’: [“”, Validators.nullValidator]

  • manoj meshram

    HI,
    haserror is not function in ionic2 beta 11.

  • EM Products

    hi, thanks for the great post
    any upcoming update for the post
    also how can I validate for retype password ??

  • Eduardo Borges

    Greate!!

  • Lior Balmas

    Thanks for the article.
    I get this error:
    “Can’t bind to ‘ngFormModel’ since it isn’t a known native property”

    I use beta.11

  • Ansar Zhalyalov

    Unfortunately doesn’t work in beta 11 – “ORIGINAL EXCEPTION: No value accessor for ””

    • Franck Didier

      +1 doesn’t work

      • An article has been updated to Ionic v2 2.2.1 version.

  • Hi, Thanks for effort, the only problem is ionic2 and angular2 have had a lot of breaking changes, also the article doesn’t have published date (or mentioning ionic2 and angular2 version that this is based on), then it will be so confusing.

    • An article has been updated to Ionic v2 2.2.1 version. Plus article always had published date; on the second page; at the beginning of the Code chapter.

      Thought; I should move this information to the first page; it makes more sense. Thank you for your observation.

  • Periyasamy M

    Thank you so much.This is working fine..particular working in latest ionic 2 version and angular 2 rc versions. Thank you once again .@gajotres

  • Tammanoon K

    Thank you for reply i’ll try this.

  • Stevenson Nelli

    Could you please provide example with ionic select field ??

  • Sanchit Mahajan

    In above form how to display variable value in username field– I have {{username}} containing user name.. I want to display that value in username field..

    • I’m just in the process of updating this article to Ionic 3, give me a few hours and I will answer your question.

    • I have updated this article. If you have time please describe me your request in more details and I will give you an answer as soon as possible.