POSTED IN Ionic Ionic 2

Ionic 2 form validation

Hi in this tutorial, we are going to see how to use Ionic 2 form validation with Typescript. Ionic 2 and Angularjs now providing libraries to handle form groups and related functionalities.
Lets see how to use Ionic 2 form validation

Step 1

Install Ionic 2 Blank template

Step 2

Goto your project directory and run ionic serve

It will run your app in local browser

Step 3

Run below comment to create login page :

It will create login folder with necessary files under src folder

Step 4

Inject components in you app.modules.ts

Step 5

Write code in your login.ts

Import Validators, FormBuilder, FormGroup from angular node modules

Step 6

Declare your form name globally as FormGroup

Inject FormGroup in your constructor

Step 7

Write validation rules inside of constructor

Here you can find other rules

Step 8

Modify your html form

A : Add “formGroup” attribute in your form
B: Add “formGroup” as defined in componets. eg [formGroup] = “login”
C: Add “ngSubmit” function in your form attribute
D: Add from input control attribute to all inputs “formControlName”
eg : formControlName=”username” & formControlName=”password”
E : Add class to modify inputs if form is invalid
eg : [class.invalid]=”!login.controls.password.valid && (login.controls.password.dirty)”
F : Disable submit button if form is not valid. eg: [disabled]=”!login.valid”

Thats it, Now you can validate your form as you want.

My login.ts file

My login.html


Ionic 2 form validation