【问题标题】:How to add required field validation on checkbox group?如何在复选框组上添加必填字段验证?
【发布时间】:2017-10-31 02:37:48
【问题描述】:

我有 4 个复选框,其中至少一个应该由用户选择。由于我是 Angular 2 的新手,所以有人可以帮我解决这个问题吗?

更新代码 sn-p:

HTML

<b><label *ngFor="let type of topics;let i=index" class="checkbox-inline">
                    <input  type="checkbox" id="{{'chkPhysician'+i}}" name="chekType"
                         formControlName="types" [value]="type.value" />
                    {{type.display}}
                    </label>

组件.ts

public topics = [
{ value: 'test1', display: 'test1',selected:true },
{ value: 'test2', display: 'test2',selected:true },
{ value: 'test3', display: 'test3',selected:true },
{ value: 'test4', display: 'test4',selected:true },

];

constructor(private fb: FormBuilder) { }
ngOnInit(): void {
    this.mirForm = this.fb.group({
        date: [this.date, Validators.required],
        Name: ['', [Validators.required, Validators.minLength(4)]],
        Mobile: ['', [Validators.required, Validators.minLength(10)]],
        Email: ['', [Validators.required, Validators.pattern('[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+')]],
        types:'', etc..............

【问题讨论】:

  • 嗨 Kiruba,请添加您目前拥有的代码,以便其他用户了解您的工作内容
  • @amura.cxg 我已经添加了示例代码。

标签: angular validation checkbox angular2-forms required


【解决方案1】:

使用change 事件

<div>
  Pick your favorite hero
  (<label><input type="checkbox" checked (change)="showSad = !showSad">show sad</label>)
</div>

或者您可以尝试使用CheckboxRequiredValidator

【讨论】:

    【解决方案2】:

    您有几个问题...如果您希望能够选中多个复选框,您实际上需要一个表单数组,而不仅仅是一个表单控件。

    然后我会检查自定义验证器是否选中了至少一个复选框。所以表单的构建应该如下所示(缩短):

    this.mirForm = this.fb.group({
      types: this.fb.array([])
    }, {validator:this.checkIfChecked});
    

    然后你会得到你的复选框,然后我们会寻找点击事件并查看复选框是选中还是未选中。基于这些,我们要么向表单数组添加表单控件,要么移除表单控件。

    <input  type="checkbox" 
            (click)="addRemoveToArr(type.value, $event.target.checked)" 
            id="{{'chkPhysician'+i}}" 
            name="chekType"
            [value]="type.value" 
    />
    

    和功能:

    addRemoveToArr(type:string,isChecked:boolean) {
      const types = <FormArray>this.myForm.get('types')
      if (isChecked){
        types.push(new FormControl(type))
      }
      else {
        let index = types.controls.findIndex(x => x.value == type)
        types.removeAt(index)
      }
    }
    

    最后是自定义验证器,如果至少选中一个复选框,则返回 null,否则返回 notValid 错误。

    checkIfChecked = (control: AbstractControl) => {
      if(control.controls.types.length == 0) {
        return {notValid:true}
      } else {
        return null;
      }    
    };
    

    【讨论】:

    • 非常感谢您的回复。我在 checkIfChecked 低于 error.file 时遇到问题:严重性:'错误'消息:'AbstractControl' 类型上不存在属性'控件'。在:'79,21' 来源:'ts'
    • 您能否在 plunker 中重现该问题,因为此代码对我来说很好:plnkr.co/edit/IOD3LUMWR7Wlb4uvv4Zp?p=preview :)
    • 它现在可以在代码中稍作更改。但是原始/触摸/脏不适用于复选框。你能帮我解决这个问题吗?
    • 您需要进行哪些更改,很好奇,因为我们可以看到 plunker 运行良好 :) 您的后续问题很有趣。今天我有更多时间的时候,我必须仔细看看某个地方! :) 我会告诉你的。
    • 它在 Visual Studio 代码编辑器中不起作用。所以我添加了一行代码,如下所示。让 typesArray = c.get("type"); if (typesArray.controls.length == 0) { return { 'notValid': true } }
    猜你喜欢
    • 2017-03-13
    • 2021-07-10
    • 2010-10-15
    • 1970-01-01
    • 2015-01-15
    • 1970-01-01
    • 2017-01-08
    • 1970-01-01
    • 2022-11-22
    相关资源
    最近更新 更多