验证angular4中的多个复选框

时间:2019-10-14 13:17:58

标签: angular

有人能告诉我如何验证多个复选框吗?用户应在加载时间中至少选择一个。如果用户未选中该复选框,则需要显示错误消息

谢谢

1 个答案:

答案 0 :(得分:0)

使用反应形式,您可以执行以下操作:

    form: FormGroup;

    constructor(private fb: FormBuilder) {}

    ngOnInit() {
        this.form = this.fb.group(
            {
                first: new FormControl(),
                second: new FormControl(),
                third: new FormControl(),
            },
            { validator: this.customValidator },
        );
    }

    customValidator(control: AbstractControl) {
        const first = control.get('first');
        const second = control.get('second');
        const third = control.get('third');
        return first.value || second.value || third.value ? null : 'Invalid';
    }

在模板中:

<div [formGroup]="form">
  <input type="checkbox" formControlName="first">
  <input type="checkbox" formControlName="second">
  <input type="checkbox" formControlName="third">
  <button [disabled]="!form.valid">Submit</button>
</div>