Ionic 7 Angular Form Validation using Reactive Forms Tutorial

Last Updated on by in Ionic

In this step by step Ionic Forms validation tutorial, we will learn how to create and validate an Angular form using Reactive Forms APIs in Ionic application.

Setting up forms in an Ionic application is easy, Angular offers Template-driven and Reactive Forms methods to deal with the forms data.

Template-driven approach is used for working with simple forms. On the other hand, It empowers developers to manage more complex data. Especially when you need to work with nested values.

We will create a basic form with following input fields name, email, and mobile number in Ionic Angular application using Angular Forms APIs.

We will use FormControl, FormGroup, FormBuilder, and Validators service to validate the form data.

FormGroup: A FormGroup is a collection of single or multiple FormControls and declared on the HTML’s form tag. Basically, its a collection of various form controls.

FormBuilder: The FormBuilder service refers to a form object and sets up a FormGroup. It holds the user entered values and validation state of a form input field.

Set Up Ionic Project

Ionic CLI has to be installed on the development machine, and you can use the following command to install or update the tool:

sudo npm install -g @ionic/cli

To setup a form in an Angular/Ionic app, you need to run the below command.

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

Get inside the project directory.

cd ionic-form-validation

Run the below command to add the native core package.

npm install @ionic-native/core --legacy-peer-deps

Disable Strict Type Errors

To avoid TypeScript compiling issues, we just need to open tsconfig.json file:

First, set below property under “compilerOptions” property.

"compilerOptions": {
    "strictPropertyInitialization": false,
    "skipLibCheck": true,
    "noImplicitReturns": false,
    ...
}

Secondly, add given props under “angularCompilerOptions”.

"angularCompilerOptions": {
    "strictTemplates": false,
    ...
}

Import & Register ReactiveFormsModule

To work with Reactive Forms in Ionic, you have to import and register FormsModule, ReactiveFormsModule along with .

Open home.module.ts and add the below code in it.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IonicModule } from '@ionic/angular';
import { HomePage } from './home.page';
import { HomePageRoutingModule } from './home-routing.module';

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [
    CommonModule,
    IonicModule,
    HomePageRoutingModule,
    FormsModule,
    ReactiveFormsModule
  ],
  declarations: [HomePage]
})

export class HomePageModule {}

Create and Validate Angular Form in Ionic

To set up a form in Ionic use Ionic form UI components. In the below section, we are creating a simple form for users; where users can fill information about theirselves using the form UI component.

Similarly, we are using the *ngIf tag to validate the form control through the Ionic HTML template.

Open home.page.html file and add the following code inside of it.

<ion-header>
  <ion-toolbar>
    <ion-title>Ionic Angular Reactive Form Example</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <form [formGroup]="ionicForm" (ngSubmit)="submitForm()" novalidate>
    <ion-item lines="full">
      <ion-label position="floating">Name</ion-label>
      <ion-input
        formControlName="name"
        type="text"
        aria-label="Name"
      ></ion-input>
    </ion-item>

    <div
      *ngIf="this.ionicForm.controls?.name.touched && this.ionicForm.controls?.name.invalid"
    >
      <div
        class="ion-padding"
        *ngIf="this.ionicForm.controls?.name.errors?.required"
      >
        <ion-text color="danger">Name is required.</ion-text>
      </div>
      <div
        class="ion-padding"
        color="danger"
        *ngIf="this.ionicForm.controls?.name.errors?.minlength"
      >
        <ion-text color="danger">Name should be min 2 chars long.</ion-text>
      </div>
    </div>

    <ion-item lines="full">
      <ion-label position="floating">Email</ion-label>
      <ion-input
        formControlName="email"
        aria-label="Email"
        type="email"
      ></ion-input>
    </ion-item>
    <div
      *ngIf="this.ionicForm.controls?.email.touched && this.ionicForm.controls?.email.invalid"
    >
      <div
        class="error ion-padding"
        *ngIf="errorControl.email.errors?.required"
      >
        <ion-text color="danger">Email is required.</ion-text>
      </div>
      <div class="ion-padding" *ngIf="errorControl.email.errors?.pattern">
        <ion-text color="danger">Please provide valid email.</ion-text>
      </div>
    </div>

    <ion-item lines="full">
      <ion-label position="floating">Mobile</ion-label>
      <ion-input
        maxlength="10"
        formControlName="mobile"
        type="text"
        aria-label="Mobile"
        required
      ></ion-input>
    </ion-item>
    <div
      *ngIf="this.ionicForm.controls?.mobile.touched && this.ionicForm.controls?.mobile.invalid"
    >
      <div
        class="error ion-padding"
        *ngIf="errorControl.mobile.errors?.required"
      >
        <ion-text color="danger">Mobile number is required.</ion-text>
      </div>
      <div
        class="error ion-padding"
        *ngIf="errorControl.mobile.errors?.pattern"
      >
        <ion-text color="danger">Only numerical values allowed.</ion-text>
      </div>
    </div>

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

Furthermore, we are going to implement the Reactive form validation in Ionic. Hence, update 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 {
  ionicForm: FormGroup;

  constructor(public formBuilder: FormBuilder) {}

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

  get errorControl() {
    return this.ionicForm.controls;
  }

  submitForm = () => {
    if (this.ionicForm.valid) {
      console.log(this.ionicForm.value);
      return false;
    } else {
      return console.log('Please provide all the required values!');
    }
  };
}

Import Validators service in the Ionic template, It provides built-in methods to validate form controls.

The Validators class offers following methods to manage form validation in Ionic / Angular.

Start the Ionic app.

ionic serve -l

Ionic 7 Angular Form Validation using Reactive Forms Tutorial

Conclusion

In this detailed guide, we learned how to profoundly implement form validation in an Ionic 7 application using Angular’s Reactive Forms approach.

By following the tutorial, developers can obtain a deep understanding of the concepts and intuitive techniques imperative to create robust and user-friendly forms.

Throughout the tutorial, we explored the key aspects of form validation, including setting up form controls, applying validators, displaying error messages, and handling form submission.

The Reactive Forms approach allows for declarative and dynamic validation, enabling developers to easily define validation rules and react to changes in real-time.

Ionic’s integration with Angular makes it a powerful framework for building cross-platform applications with a consistent user experience.

The tutorial showcases the seamless integration of Ionic components and Angular’s Reactive Forms, providing developers with a flexible and efficient way to validate user input and ensure data integrity.