2016-05-23 85 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>