Ionic 3 validation is not working on “invalid && dirty”


#1

I’m using Template Driven Angular Forms and I;m wanting to display an error in a div if the user touches the form element, but nothing is showing.

<ion-item class="formField">
        <ion-label color="primary" stacked>Start Date</ion-label>
        <ion-datetime
        type="date"
        name="startDate"
        id="startDate"
        displayFormat="MM/DD/YYYY"
        ngModel
        #startDate="ngModel">
        </ion-datetime>
      </ion-item>
        <div>
        <ion-label *ngIf="startDate.invalid && dirty">Test</ion-label>
      </div>

I was testing with different approaches, but I could never get the div to show with no errors. Is this functionality not working in ionic or am I doing something wrong? I was thinking about using Reactive Forms, but I wanted to be sure this wasn’t working first.


#2

I think startDate.invalid && dirty should be startDate.invalid && startDate.dirty


#3

Even if I just use

  <ion-label *ngIf="startDate.invalid">Test</ion-label>

Nothing shows up.


#4

With that picker, it might not be possible to be invalid, since it controls the input.

You will note the change to the [(ngModel)] to bind it to a variable so you can use the data from the element.

<ion-item class="formField">
    <ion-label color="primary" stacked>Start Date</ion-label>
    <ion-datetime type="date" name="startDate" id="startDate" displayFormat="MM/DD/YYYY" [(ngModel)]="myDate" #startDate="ngModel">
    </ion-datetime>
  </ion-item>
  <div>
      <ion-label *ngIf="startDate.touched">Touched</ion-label>
      <ion-label *ngIf="startDate.dirty">Dirty</ion-label>
      <ion-label *ngIf="startDate.valid">Valid</ion-label>
      <ion-label *ngIf="startDate.invalid">Invalid</ion-label>
  </div>

#5

So for some reason it wasn’t working one day, and now it’s working fine. Thank you for clarification!


#6

It’s good to clear (delete www and .sourcemaps folders) and rebuild your project now and then during (live) development (when it really really really should be working)

Works for me when I’m getting unexpected behaviours like this.