Angular2:使用FormBuilder Validators.required和复选框组的最佳方法

时间:2016-05-23 16:01:28

标签: forms checkbox angular

我使用FormBuilder&amp ;;在Angular2中构建表单ngFormModel并且无法找到验证复选框组中的一个或多个复选框的优雅方法。我不想编写自定义组件方法来验证我使用它们的任何地方的复选框组。理想情况下,将ngFormModel与FormBuilder& Validators.required甚至是自定义验证器。

2 个答案:

答案 0 :(得分:6)

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

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

和验证器:

checkboxRequired(group: FormGroup) {
  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
  };
}

答案 1 :(得分:0)

由于API略有变化。以下答案的略微更新版本。这有点冗长

{
    "status": "sent",
    "emailSubject": "...",
    "compositeTemplates": [{
        "serverTemplates": [{
            "sequence": 2,
            "templateId": "..."
        }],
        "inlineTemplates": [{
            "sequence": 1,
            "documents": [{
                "documentId": "...",
                "name": "...",
                "documentBase64": "..."
            }, {
                "documentId": "...",
                "name": "...",
                "documentBase64": "..."
            }]
        }]
    }]
}

验证功能:

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
}