Ion-checkbox breaks form validation

Angular has great form validation built in, but it seems like the ionic-checkbox stops that from working. I have a simple form with a submit button that stays disabled until the required fields are filled out, including a confirmation checkbox.

However, using an ion-checkbox like this:

<ion-checkbox name="confirmed" color="primary" class="checkbox" [(ngModel)]="test" required></ion-checkbox>

Means it’s not validated. I’m going to assume because an ion-checkbox isn’t even a checkbox at all, so Angular’s form validation can’t check if it’s checked…because…it’s not a checkbox. Changing my code to:

<input type="checkbox" name="confirmed" color="primary" class="checkbox" [(ngModel)]="test" required/>

let’s validation keep on working just fine. I’m trying to understand why the ion-checkbox wouldn’t put like a hidden checkbox on screen so validation could work. Any idea? I haven’t seen any open bugs on this, has anyone else experienced this?

Thanks,
Rob

Probably not a whole lot of solace, but <ion-checkbox> validation does work with reactive forms:

form: FormGroup;

constructor(public navCtrl: NavController, np: NavParams, fb: FormBuilder) {
  this.form = fb.group({
    frobulated: [undefined, Validators.required],
  });
}

<form [formGroup]="form">
  <ion-item>
    <ion-label>frobulated</ion-label>
    <ion-checkbox formControlName="frobulated"></ion-checkbox>
  </ion-item>
  <button ion-button [disabled]="!form.valid">submit</button>
</form>

The submit button is disabled until the “frobulated” checkbox is either true or false.

Thank you, I haven’t messed with reactive forms yet, but we may end up making the switch for a different validation reason.

Good info. For the time being I simply disable my submit button until the form is valid and the value bound to the checkbox is true. Shouldn’t be necessary but works for now. Thanks again for the info, this is very good to know.

use Validators.requiredTrue instead of just Validators.required

2 Likes

In my case, it worked with:
frobulated: ['false', Validators.requiredTrue]

1 Like