Ionic form validations


#1

Hello ,

In my ionic form, I have 2 ion-input fields and one ion-select field. so I want to validate form all fields are required. how to do that?


#2

This is your view.html:

<ion-content padding>

    <ion-list>
        <form #myForm="ngForm" (ngSubmit)="postData()">
            <ion-item>
                <ion-label floating>Name</ion-label>
                <ion-input type="text" [(ngModel)]="users.name" id="name" name="name" required #name="ngModel"></ion-input>

            </ion-item>
            <span *ngIf="name.errors">
                <span [hidden]="!name.errors.required">
                    <ion-label style="color: red; margin-left: 16px;"> Name is required </ion-label>
                </span>
            </span>

            <ion-item>
                <ion-label floating>Email</ion-label>
                <ion-input type="email" id="email"  [(ngModel)]="users.email"  name="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$" required #email="ngModel"  ></ion-input>
            </ion-item>
            <span *ngIf="email.errors">
                <span [hidden]="!email.errors.required">
                    <ion-label style="color: red; margin-left: 16px;"> Email is required </ion-label>
                </span>
                <span [hidden]="!email.errors.pattern">
                    <ion-label style="color: red; margin-left: 16px;"> Please enter a valid email </ion-label>
                </span>
            </span>

            <ion-item>
                <ion-label floating>Contact</ion-label>
                <ion-input type="number" id="contact" [(ngModel)]="users.contact" name="contact" required #contact="ngModel"></ion-input>
            </ion-item>
            <span *ngIf="contact.errors">
                <span [hidden]="!contact.errors.required">
                    <ion-label style="color: red; margin-left: 16px;"> Contact is required </ion-label>
                </span>
            </span>

            <ion-item>
                <button [disabled]="!myForm.form.valid" type="submit" ion-button block>Submit</button>
            </ion-item>
        </form>
    </ion-list>
</ion-content>

This is your component.ts:

export class AddCustomerPage {

    private dataArray: any[];
    private users = {
        name: '',
        contact: '',
        email: ''
    };
}

Maybe this will help you :slight_smile:


#3

Thanks for the quick replay

I am getting below error


#4
import {Validators, FormBuilder, FormGroup } from '@angular/forms';

add this in your module.ts or component.ts and refer the below link:


#5

Thanks for replay,

I am able to get the required field validation only when I enter text and removed. but I want to show error message on button click. without touching any input field

image

see the code


<ion-header>

  <ion-navbar>
    <ion-title>Portal dayrec and exp</ion-title>
  </ion-navbar>

</ion-header>

<ion-content padding>
  <section>
    <ion-item-group>
      <ion-item-divider color="light">
        <h3>CS17SEP ORI 5686 <b>NW9 5EU</b></h3>
      </ion-item-divider>
      <form [formGroup]="form" (ngSubmit)="SaveChanges(form.value)">
        <ion-list no-line>
          <ion-item>
            <ion-label color="primary" floating>Ints</ion-label>
            <ion-input formControlName="Ints" type="number"></ion-input>
          </ion-item>
          <ion-item>
            <ion-label color="primary" floating>Edit Ints</ion-label>
            <ion-input formControlName="EditInts" type="number"> </ion-input>
          </ion-item>
          <ion-item>
            <ion-label color="primary" floating>Hrs</ion-label>
            <ion-select formControlName="Hrs">
              <ion-option *ngFor="let hour of hours" [value]="hour">{{hour}}</ion-option>
            </ion-select>
          </ion-item>
          <ion-item>
            <ion-label color="primary"  floating>Comment</ion-label>
            <ion-textarea></ion-textarea>
          </ion-item>
        </ion-list>

        <div>
          <button ion-button color="dark" [disabled]="!form.valid" block><span class="fontColor" >Save</span></button>
        </div>
      </form>
    </ion-item-group>
    <div padding>
      <button ion-button color="dark" block><span class="fontColor" (click)="NavigateToExpenses()" >View Expenses</span></button>
    </div>
  </section>
</ion-content>

Ts code

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@IonicPage()
@Component({
selector: 'page-portaldayrecandexp',
templateUrl: 'portaldayrecandexp.html',
})
export class PortaldayrecandexpPage {
hours: any[] = [];
_i: number;
submitAttempt: boolean = false;
public form: FormGroup;
constructor(public navCtrl: NavController,
public navParams: NavParams,
private _FB: FormBuilder) {
this.form = _FB.group({
'Ints': ['', Validators.required],
'EditInts': ['', Validators.required],
'Hrs': ['0', Validators.required]
});
}

ionViewDidLoad() {
console.log('ionViewDidLoad PortaldayrecandexpPage');
this.getHours();
}
NavigateToExpenses() {
this.navCtrl.push("ExpensesPage");
}
getHours() {
for (this._i = 0; this._i <= 48; this._i++) {
this.hours.push(this._i / 4);
}
}
SaveChanges(form) {
console.log(form);
}

}

#6

You can also check this repo which is an Ionic 3 example app to learn how to handle Forms and Validations: https://github.com/ionicthemes/ionic2-form-handling-and-validations
Hope it helps :wink:


#7

All properties accessed by templates must be public.


#8

Thank you for your suggestion. I will keep this in mind for my next functionality. But this code is working fine for me now.


#9

It should break in production. If it doesn’t, it’s only because of a side-effect of how app-scripts compiles things that you should not rely on.


#10

Atula this one is really good, really helped out me.


#11

Thanks Buddy…It wll help me