1

I have a Ionic 3 form with 3 checkboxes fields:

<form [formGroup]="bookingForm" (ngSubmit)="addBooking()">
<ion-card>
  <ion-card-content>
    <ion-item-group formGroupName="period">
      <ion-list>
        <ion-list-header>
          Select the Period:
        </ion-list-header>
        <ion-item>
          <ion-label>Morning</ion-label>
          <ion-checkbox formControlName="morning"></ion-checkbox>
        </ion-item>
        <ion-item>
          <ion-label>Afternoon</ion-label>
          <ion-checkbox formControlName="afternoon"></ion-checkbox>
        </ion-item>
        <ion-item>
          <ion-label>Night</ion-label>
          <ion-checkbox formControlName="night"></ion-checkbox>
        </ion-item>
      </ion-list>
    </ion-item-group>
  </ion-card-content>
</ion-card>
<button ion-button color="primary" block type="submit" [disabled]="!bookingForm.valid">Add</button>

I would like to validate if the user select one least checkbox.

This is my TS file with the form builder code:

  constructor(
    private formBuilder: FormBuilder
  ) {
    this.bookingForm = this.formBuilder.group({
      //... other fields in the form ...
      period: this.formBuilder.group(
        {
          morning: false,
          afternoon: false,
          night: false
        },
        Validators.requiredTrue
      )
    });
  }

The validator doesn't work as expected. The Add button are enabled by default and the user can submit the form without selected any checkbox.

Joel
  • 974
  • 2
  • 10
  • 18

1 Answers1

1

You need to write a group validator:

  constructor(
    private formBuilder: FormBuilder
  ) {
    this.bookingForm = this.formBuilder.group({
      //... other fields in the form ...
      period: this.formBuilder.group(
        {
          morning: false,
          afternoon: false,
          night: false
        },
        { 
           validator: (c: AbstractControl)=> {
           if (!c.get('morning').value &&
               !c.get('afternoon').value && 
               !c.get('evening').value)
               return { pickone: true};
          return null;
          }
       })
    });
  }
Michael Kang
  • 52,003
  • 16
  • 103
  • 135
  • Thanks for reply. "Validators.requiredTrue" aren't a valid group validator? Do I need to create a custom group validator for this purpose? – Joel May 09 '18 at 12:42