Skip to content

Ionic 2 Forms – FormBuilder and Validation

Posted in Javascript

I am in a hurry, so let’s do this quick. Shall we?

The Ionic 2 series is coming up nicely, and today, we’re going to discuss how to use the FormBuilder Class and Validators in our forms. Just like the previous steps in creating form Controls and ControlGroups implicitly using ngForm were straight to the point, I hope this one is as equally fun.

Update: In Ionic 2 Beta.11 using AngularJS RC4, how FormBuilder is used along with FormGroup  and other form classes change a bit. Find the update at

One of the newbie questions with Ionic 2 is how to get Ionic 2 Side menu and Tabs combined. I discuss the how-tos of that in my Ionic 2 Side Menu and Tabs article.



What we already know

It was just amazing how easy it is to create forms in Angular 2 (Ionic 2 for that matter), as we witnessed in our previous discussion. ngForms created implicitly a ControlGroup for us, which we could pass in the form input values, or the Control into the onSubmit() function we called, which posted a mere console message with the form data.

This form data, we decided to post to the console, but what could be done with it is pretty much endless. You could use the data, if from a login form, to authenticate, or create a new user profile, and many others.

All the simple and basic understanding you gained from the other article is going to help with this one too. So let’s take it slow, and get ionized!

What we want and What we’ll do

Creating a form implicitly isn’t always what you or I might want. Sometimes we want to take control of the ‘Controls’ and get down to the nitty-gritty parts. It is fun! Angular 2 doesn’t leave all the fun for itself. With FormBuilder and Validators, Angular 2 hands over the driving wheel to you. As to what you do, that’s none of its business. Who cares what you do with a Hadron Collider!


The final code for our basic Ionic 2 Forms is on Github. If you missed the previous tutorial, you can check it out, it adds flesh to the code and discusses it.

Again, let’s quote the NG-Book 2 here. I can’t stress enough how good the book is. It was written for Angular 2, in Typescript, but since Ionic 2 dances with Angular 2, the concert is just as harmonious as you would expect.

Building our Controls and ControlGroups implicitly using ngForm and ngControl is convenient, but doesn’t give us a lot of customization options. A more flexible and common way to configure forms is to use a FormBuilder .
FormBuilder is an aptly-named helper class that helps us build forms. As you recall, forms are made up of Control s and ControlGroup s and the FormBuilder helps us make them (you can think of it as a “factory” object).

Think of ngForm and ngControl as autopilot and FormBuilder as manual control. We want manual control this time.

The quote from the NG-Book puts everything in perspective just the way needed to jump right into the code. So, shall we?

How gorgeous! Taking the steering manually didn’t mean we’re gonna press a million buttons and drive several pedals and gear handles to get the plane to move an inch.

It simply meant, manually creating a ControlGroup using the .group() function of the formBuilder instance auto created for us after injecting it and its related metadata. The two fields provided are essentially the form fields we’ve got or in other words, our ngControls. It doesn’t get any simpler than this, does it?

Now, what changes do we expect to see in the template? Some say I talk too much, so, please, here we go:

You’ll have to forgive me, I need to add a word to the above, to clear what we’ve seen above. See:

With them compared head-on, I’m sure you get the picture now. With explicitly created ControlGroup, one way to intercept and use in your template is the example you see above. In Angular 1, we all know ng-model to bind an input field value to the scope. Well, the [ngFormModel] is doing something similar. So it is binding the ControlGroup to the current form in the template. Then, it exposes a ngSubmit directive for us to enjoy for free.

This cool kid in the block makes so much sense when understood. Can seem chaotic at first, but taking a deep breath, and trying to see how the pattern works is all you need to hit the jackpot.

I doubt I need to write anything to explain what that is. In English:

I created a control group called myForm, I also created controls, two for that matter in this myForm control group. Please, find the one called ‘subject’, via key search, and bind to the input field in context.

Validation! Duh…

We’re done with using FormBuilder this quick. Did I miss anything? Hmmmmm…. Lemme see. Not that I know of. Remember, my goal is to share the easiest, simplest form of tricks in using Ionic 2 Forms.

Thus, using FormBuilder was pretty straightforward, and if you had sweat on your face at the end of that section, then it wasn’t my fault. So, Validation…

We will be simply extending the example above to include the validations. I will include the parts you’ll need to change only. So, please, open your eyes, the real ones.

We add extra imports, namely and specifically, Validators Don’t keep wondering what magic Validators bring on board. You’ll see soon. In fact, now!

You see what we’re doing there? In our previous code, we had something like this, ... 'subject': '', but here, we’re adding brackets instead. Well, each Control takes accepts array too, if you wanna add multiple options.

NOTE: If you played with the formBuilder controls key-value in the previous example, the value part, you would have noticed that, what you put in the 'subject': 'input value' – the string ‘input value’ will be prepopulated in your templates when reloaded. With this approach, you could prepopulated a form with data from say, the server by passing them into whatever form control as the first item.

Quoting ng-book:

The most flexible way to deal with individual Controls in your view is to set each Control up as an instance variable in your Component [or Page] definition class.

To that effect, this is how we would do it:

The above gives us both controls in our template to dance, sing and play with. It is that easy, and manipulating in the template will happen like this:

That’s a lot to look at, so let’s break things down a bit.

That’s where the focus is. Before you get confused, remember we added both form controls, ‘subject’ and ‘message’ to an instance variable called subject and message in our controller? They are the one’s you’re seeing used in action here, in the form of !subject.valid etc.




So, in English, taking the first line first:

If my form control, the explicitly created one passed from the controller, which is same as if we used ngControl, if that control isn’t valid and has been touched, display, “Subject is empty”

Since we are using an && (AND) operator here, we expect both conditions to be true for the element to be shown. When the page is loaded the first time, subject.touched is false. We haven’t interacted with that input field. In addition, !subject.valid evaluates to false again, because, well, our form input “requires” something to be put in. So, we have two false statements. Our error message doesn’t get to show. Win!

Note: Browser standard validators like:

  • Required
  • minLength
  • maxLength

are allowed on an ionic field. We’re even using the required

However, try leaving the input field focus with nothing in the field, then you’ll be shown the error message because 1) You’ve touched the field, and 2) it is empty, although required. Am I right? I might be confused at this point, but I am sure you get the point.

The throwing in of the subject.touched explains another type of way to validate your form, via interactions. So if the field has been touched, say something, if not, who cares, the user isn’t probably ready.

The above example covers only a tiny part of what validation combos could be achieved. For example, you could decide to disable the add button until everything in the form checks out. So  something like this on the ion button

… which is simply saying, at least, one of the input fields should be unblemished. Pure win, for everyone involved. Remember, though, such hiding of the button does not necessarily mean what the user sends is what you wanted. Your validation might check for allowing only alphanumeric input value. It is important to check everything again on the server before saving to DB unless you don’t care what comes in.

In an app, it might be hard or perhaps uncommon for someone unhiding a button so as to go ahead and send something, but if building apps with AngularJS that’ll run in the browser, remember a user could just open the code inspector and tweak things to suit their needs to enable the button.

At this point, under the validations, this is what we can end up with:

Then formvalidate.js? Here:

Well, that was just by the way, but if there are points you take home from this article, they likely might be:

  • Explicitly building a ControlGroup and Controls using FormBuilder is straightforward and easy too.
  • The power of validation is always in your hands. Dance with it however you like.

Thanks for your time, and make sure to check out the source code for the entire examples above on Github. Please, feel free to draw my attention to any mistakes herein. Still on the learning curve with Ionic 2, and will appreciate expert tips and guidance, if and when I’m going wrong.