Form Validation in Ionic 6 with Reactive Forms

In this Angular Ionic Forms Validation tutorial, we will see how to validate forms in Ionic using Reactive Forms.

Any application is incomplete without implementing forms; forms make the communication between user and server through data transmission.

Reactive Forms helps you efficiently build the Forms; you can implement input level validation with it too.

Reactive forms provide a model-driven approach to handling form inputs whose values change over time.

There are two methods to handle forms in Angular Ionic, template-driven and reactive forms.

In this tutorial, we will use Reactive forms to build and validate forms. We will also create an Ionic app from scratch and add validation rules for the name, email, date of birth, and phone number.

Let’s get started.

Create Ionic App

Let’s create Ionic app:

ionic start ionic-form-validation-example blank --type=angular

Get into the project root.

cd ionic-form-validation-example

To test the app install lab mode:

npm i @ionic/lab --save-dev

Remove Type Errors

You have to remove strict type errors make sure to set “strictTemplates”: false in angularCompilerOptions in tsconfig.json file.

Import ReactiveFormsModule in Ionic

Import angular’s ReactiveFormsModule and FormsModule APIs in home.module.ts file, It allows you to create the Form in Ionic.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IonicModule } from '@ionic/angular';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';

import { HomePage } from './home.page';

@NgModule({
  imports: [
    CommonModule,
    ReactiveFormsModule,
    FormsModule,
    IonicModule,
    RouterModule.forChild([
      {
        path: '',
        component: HomePage
      }
    ])
  ],
  declarations: [HomePage]
})

export class HomePageModule { }

Validate Form in Ionic

Reactive forms offers better control for handling forms, we are creating and validating Forms in Ionic application.

So, add the following code in home.page.ts file:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from "@angular/forms";

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})

export class HomePage implements OnInit {
  myForm: FormGroup;
  submitted = false;

  constructor(public formBuilder: FormBuilder) { }

  ngOnInit() {
    this.myForm = this.formBuilder.group({
      name: ['', [Validators.required, Validators.minLength(3)]],
      email: ['', [Validators.required, Validators.pattern('[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$')]],
      dob: [],
      phone: ['', [Validators.required, Validators.pattern('^[0-9]+$')]]
    })
  }

  fetchDate(e) {
    let date = new Date(e.target.value).toISOString().substring(0, 10);
    this.myForm.get('dob').setValue(date, {
      onlyself: true
    })
  }

  get errorCtr() {
    return this.myForm.controls;
  }

  onSubmit() {
    this.submitted = true;
    if (!this.myForm.valid) {
      console.log('All fields are required.')
      return false;
    } else {
      console.log(this.myForm.value)
    }
  }
}

Place the following code in home.page.html:

<ion-header>
  <ion-toolbar>
    <ion-title>Ionic Forms</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <form [formGroup]="myForm" (ngSubmit)="onSubmit()" novalidate>

    <ion-item lines="full">
      <ion-label position="floating">Name</ion-label>
      <ion-input formControlName="name" type="text"></ion-input>
    </ion-item>
    <span class="error ion-padding" *ngIf="submitted && errorCtr.name.errors?.required">
      Name is required.
    </span>
    <span class="error ion-padding" *ngIf="submitted && errorCtr.name.errors?.minlength">
      Min 3 chars long.
    </span>

    <ion-item lines="full">
      <ion-label position="floating">Email</ion-label>
      <ion-input formControlName="email" type="email"></ion-input>
    </ion-item>
    <span class="error ion-padding" *ngIf="submitted && errorCtr.email.errors?.required">
      Email is required.
    </span>
    <span class="error ion-padding" *ngIf="submitted && errorCtr.email.errors?.pattern">
      Enter valid email.
    </span>

    <ion-item lines="full">
      <ion-label position="floating">DOB</ion-label>
      <ion-datetime (ionChange)="fetchDate($event)" formControlName="dob" [value]="defaultDate"></ion-datetime>
    </ion-item>

    <ion-item lines="full">
      <ion-label position="floating">Phone</ion-label>
      <ion-input maxlength="10" formControlName="phone" type="text" required></ion-input>
    </ion-item>
    <span class="error ion-padding" *ngIf="submitted && errorCtr.phone.errors?.required">
      Phone number is required.
    </span>
    <span class="error ion-padding" *ngIf="submitted && errorCtr.phone.errors?.pattern">
      Number values allowed.
    </span>

    <ion-row>
      <ion-col>
        <ion-button type="submit" color="danger" expand="block">Submit</ion-button>
      </ion-col>
    </ion-row>
  </form>
</ion-content>

Run Ionic Form Application

Start the Ionic form validation app.

ionic serve -l

Form Validation in Ionic with Reactive Forms

Download the full code of this tutorial from GitHub.