Validation on a list of checkboxes Angular 2
Asked Answered
B

1

5

I have a list of business units that are rendered as checkboxes on a registration form along with a textbox field and am doing validation.

 <label for="inputFirstName" class="sr-only">First name</label>
<input type="text" formControlName="firstName" class="form-control" placeholder="First name">

 <div class="checkbox" *ngFor="let bu of businessUnits">
        <label><input type="checkbox" #instance value="{{bu.BuName}}" (click)="getCheckBoxValue(instance.checked, bu.BuName)">{{bu.BuName}}</label>
    </div>

The list of business units are retrieved from a database table and it is rendered when the form loads

businessUnits: BusinessUnit[] = [];

In the constructor I am validating the email like this

  "firstName": new FormControl('', [Validators.required]),

})

How would I go about in validating that at least one check box of the list of checboxes the were loaded dynamically on page load is checked?

Thanks

Burgoo answered 4/2, 2017 at 8:14 Comment(2)
If I understand correctly, you want to check at least one checkbox at page load. So try this ou adapt this code after you retrieve your data on Init : this.yourForm.patchValue({'buName': this.businessUnits[0]}, {onlySelf: true})Cyanotype
@Cyanotype no, unfortunately you misunderstood, he wants at least 1 checkbox to be selected (by the user) on form submit. He doesn't want to prefill a checkbox to be selected programmatically.Whipping
I
8

let try this demo: https://stackblitz.com/edit/angular-custom-form-validation?file=app/app.component.ts

the 2nd param will accept validator function, just pass like this

this.fg = this.fb.group({
  firstName: ['', [Validators.required]],
  bUnits: this.fb.array(
    this.businessUnits.map(() => this.fb.control('')),
    CustomValidators.multipleCheckboxRequireOne
  )
});

AppComponent

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormArray, FormBuilder, Validators } from '@angular/forms'

import { CustomValidators } from './custom.validators';

@Component({
  selector: 'app-root',
  template: `
    <form (ngSubmit)="onSubmit()" novalidate [formGroup]="fg">
      <div><input type="text" formControlName="firstName" class="form-control" placeholder="First name"></div>
      <div formArrayName="bUnits">
        <div *ngFor="let unit of fg.controls.bUnits.controls; let i = index;">
          <p>Unit {{ i + 1 }}</p>
          <div>
            <label>
              <input type="checkbox" [formControlName]="i" [value]="businessUnits[i].value">
              {{businessUnits[i].name}}
            </label>
          </div>
        </div>
      </div>

      <button type="submit">Submit</button>
      <p>Status {{ fg.valid }}</p>
    </form>
  `
})
export class AppComponent implements OnInit {
  fg: FormGroup;
  businessUnits: any[] = [];

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    // do some stub to grab data
    this.businessUnits = [
      {name: 'BU 1', value: "1"},
      {name: 'BU 2', value: "2"},
      {name: 'BU 3', value: "3"}
    ];
    this.fg = this.fb.group({
      firstName: ['', [Validators.required]],
      bUnits: this.fb.array(
        this.businessUnits.map(() => this.fb.control('')),
        CustomValidators.multipleCheckboxRequireOne
      )
    });

  }

  onSubmit() {
    console.log(this.fg);
  }
}

CustomValidators

import { FormArray } from '@angular/forms';

export class CustomValidators {
  static multipleCheckboxRequireOne(fa: FormArray) {
    let valid = false;

    for (let x = 0; x < fa.length; ++x) {
      if (fa.at(x).value) {
        valid = true;
        break;
      }
    }
    return valid ? null : {
      multipleCheckboxRequireOne: true
    };
  }
}
Impanation answered 4/2, 2017 at 10:22 Comment(2)
Tiep, plunker demo is not loading. Could you please fix it?Kroon
If I understand correctly, it require one checkbox to be select and it will enable the checkbox right ?Alyose

© 2022 - 2024 — McMap. All rights reserved.