2016-05-23 71 views

回答

5

您需要定义一组为您的复选框,并指定一组验证:

this.myForm = this.builder.group({ 
    'checkboxes': fb.group({ 
    checkbox1: [ '' ], 
    checkbox1: [ '' ] 
    }, {validator: this.checkboxRequired}) 
}); 

和验证:

checkboxRequired(group: ControlGroup) { 
    var valid = false; 

    for (name in group.controls) { 
    var val = group.controls[name].value; 
    if (val) { 
     valid = true; 
     break; 
    } 
    } 

    if (valid) { 
    return null; 
    } 

    return { 
    checkboxRequired: true 
    }; 
} 

您可以用表格这种方式链接此:

<form [ngFormModel]="myForm"> 
    Checkbox1: <input type="checkbox" 
    [ngFormControl]="myForm.controls.checkboxes.controls.checkbox1"/> 
    Checkbox2: <input type="checkbox" 
    [ngFormControl]="myForm.controls.checkboxes.controls.checkbox2"/> 
</form> 

查看此问题以了解更多详情:

你可以提高验证码借力Validators.required

checkboxRequired(group: ControlGroup) { 
    var valid = false; 

    for (name in group.controls) { 
    var check = Validators.required(group.controls[name]); 
    if (!check) { 
     valid = true; 
     break; 
    } 
    } 

    if (valid) { 
    return null; 
    } 

    return { 
    checkboxRequired: true 
    }; 
} 
0

由于API已经略有改变。以下答案稍微刷新一下。这是有意的有点冗长

this.myForm = this._fb.group({ 
     myName: ['', [<any>Validators.required, <any>Validators.minLength(5)]], 
     role: new FormGroup({ 
      prog: new FormControl(null), 
      mgr: new FormControl(null), 
      designer: new FormControl(null), 
      }, this.CheckGroupValidation) 
    }); 

的验证功能:

private CheckGroupValidation(group:FormGroup) 
 
{ 
 

 
    var valid = false; 
 
    var control_name:any; 
 

 

 
    for (control_name in group.controls) 
 
    { 
 
     var check = group.controls[control_name].value; 
 
     if (check) { valid = true; break; } 
 
    } 
 

 
    if (valid) { return null;} 
 
    return { CheckGroupValidation: true}; // not qualified 
 
}

模板文件

<form [formGroup]="myForm" novalidate (ngSubmit)="save()" > 
 

 
<ion-list> 
 

 
    <ion-item> 
 
     <ion-label>Username</ion-label> 
 
     <ion-input type="text" value="" formControlName="myName" ></ion-input> 
 
    </ion-item> 
 

 

 
</ion-list> 
 

 
<ion-list formGroupName="role"> 
 
    <ion-item> 
 
     <ion-label>Programmer</ion-label> 
 
     <ion-checkbox color="dark" checked="true" formControlName="prog" ></ion-checkbox> 
 
    </ion-item> 
 

 
    <ion-item> 
 
     <ion-label>Manager</ion-label> 
 
     <ion-checkbox color="dark" checked="false" formControlName="mgr"></ion-checkbox> 
 
    </ion-item> 
 

 
    <ion-item> 
 
     <ion-label>Designer</ion-label> 
 
     <ion-checkbox color="dark" checked="false" formControlName="designer"></ion-checkbox> 
 
    </ion-item> 
 

 
</ion-list> 
 

 
<button type="submit" 
 
     [disabled] = "!myForm.valid" 
 
     [hidden]= "isProcessing" 
 
     ion-button full style="margin-top:0px;" >Submit</button> 
 
</form>