Ionic 3选中至少一个复选框

时间:2018-05-09 01:14:32

标签: angular forms typescript ionic-framework

我有一个带有3个复选框字段的Ionic 3表单:

box = () => {
  <div style={{visibility: this.state.visibility}}>
    <Input type= 'text' />
    <Button onClick={() => {this.hideBox()}}>Send</Button>
  </div>
}
showBox = () => {
  this.setState({visibility: 'visible'});
}
hideBox = () => {
  this.setState({visibility: 'hidden'});
}
render(){
  return(
    <div>
      <Button onClick={() => {this.showBox()}}>Show</Button>
      {this.box()}
    </div>
  )
}

我想验证用户是否选择了至少一个复选框。

这是我的TS文件,其中包含表单构建器代码:

<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>

验证程序无法按预期工作。默认情况下启用“添加”按钮,用户可以在不选中任何复选框的情况下提交表单。

1 个答案:

答案 0 :(得分:1)

您需要编写一个组验证器:

  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;
          }
       })
    });
  }