How to validate that at least one checkbox should be selected?

at least one checkbox checked validation in html5
multiple checkbox validation in javascript with example
single checkbox validation in javascript
select at least two checkbox validation in javascript
codeigniter form validation for checkbox at least one selection
laravel validate checkbox at least one
multiple checkbox validation in javascript w3schools
parsley at least one checkbox checked

I want to do validation for checkboxes here without form tag. At least one checkbox should be selected.

<div *ngFor="let item of officeLIST">
  <div *ngIf=" item.officeID == 1">
    <input #off type="checkbox" id="off" name="off" value="1" [(ngModel)]="item.checked">
    <label>{{item.officename}}</label>
  </div>

  <div *ngIf="item.officeID== 2">
    <input #off type="checkbox" id="off" name="off" value="2" [(ngModel)]="item.checked">
    <label>{{item.officename}}</label>
  </div>

  <div *ngIf="item.officeID== 3">
    <input #off type="checkbox" id="off" name="off" value="3" [(ngModel)]="item.checked">
    <label>{{item.officename}}</label>
  </div>
</div>

for other field I will put required and do the error|touched|valid etc. but since checkbox is not single input, I cannot put required in every checkbox because all checkbox will be compulsory to checked. so how do I do the validation to alert user atleast one should be checked?

consider creating a FormGroup which contains your check-box group and bind the group's checked value to a hidden formcontrol with a required validator.

Assume that you have three check boxes

items = [
  {key: 'item1', text: 'value1'},      // checkbox1 (label: value1)
  {key: 'item2', text: 'value2'},      // checkbox2 (label: value2)
  {key: 'item3', text: 'value3'},      // checkbox3 (label: value3)
];

Step1: define FormArray for your check boxes

let checkboxGroup = new FormArray(this.items.map(item => new FormGroup({
  id: new FormControl(item.key),      // id of checkbox(only use its value and won't show in html)
  text: new FormControl(item.text),   // text of checkbox(show its value as checkbox's label)
  checkbox: new FormControl(false)    // checkbox itself
})));

*easy to show via ngFor

Step2: create a hidden required formControl to keep status of checkbox group

let hiddenControl = new FormControl(this.mapItems(checkboxGroup.value), Validators.required);
// update checkbox group's value to hidden formcontrol
checkboxGroup.valueChanges.subscribe((v) => {
  hiddenControl.setValue(this.mapItems(v));
});

we only care about hidden control's required validate status and won't show this hidden control in html.

Step3: create final form group contains below checkbox group and hidden formControl

this.form = new FormGroup({
  items: checkboxGroup,
  selectedItems: hiddenControl
});

Html Template:

<form [formGroup]="form">
  <div [formArrayName]="'items'" [class.invalid]="!form.controls.selectedItems.valid">
    <div *ngFor="let control of form.controls.items.controls; let i = index;" [formGroup]="control">
      <input type="checkbox" formControlName="checkbox" id="{{ control.controls.id.value }}">
      <label attr.for="{{ control.controls.id.value }}">{{ control.controls.text.value }}</label>
    </div>
  </div>
  <div [class.invalid]="!form.controls.selectedItems.valid" *ngIf="!form.controls.selectedItems.valid">
    checkbox group is required!
  </div>
  <hr>
  <pre>{{form.controls.selectedItems.value | json}}</pre>
</form>

refer this demo.

Making sure at least one checkbox is checked, Validating that at least one checkbox is checked. hi, I love the site. I was able to Any help would be appreciated. I couldn't find any video on  Struggling to figure out a clean way to validate a multiple question form. Especially a good way to check to see that at least one checkbox is checked for more than one question. I found this example that looks good but struggling to find a way to do this across multiple questions.

The accepted answer abuses stuff to use in a way they are not meant to be. With reactive forms the best, easiest and probably right way is to use a FormGroup that holds your grouped checkboxes and create a validator to check if at least one(or more) checkbox is checked within that group.

To do so just create another FormGroup inside your existing FormGroup and attach a validator to it:

form = new FormGroup({
    // ...more form controls...
    myCheckboxGroup: new FormGroup({
      myCheckbox1: new FormControl(false),
      myCheckbox2: new FormControl(false),
      myCheckbox3: new FormControl(false),
    }, requireCheckboxesToBeCheckedValidator()),
    // ...more form controls...
  });

And here is the validator. I made it so you can even use it to check if at least X checkboxes are checked, e.g. requireCheckboxesToBeCheckedValidator(2):

import { FormGroup, ValidatorFn } from '@angular/forms';

export function requireCheckboxesToBeCheckedValidator(minRequired = 1): ValidatorFn {
  return function validate (formGroup: FormGroup) {
    let checked = 0;

    Object.keys(formGroup.controls).forEach(key => {
      const control = formGroup.controls[key];

      if (control.value === true) {
        checked ++;
      }
    });

    if (checked < minRequired) {
      return {
        requireCheckboxesToBeChecked: true,
      };
    }

    return null;
  };
}

In your template don't forget to add the directive 'formGroupName' to wrap your checkboxes. But don't worry, the compiler will remind you with an error-message if you forget. You can then check if the checkbox-group is valid the same way you do on FormControl's:

<ng-container [formGroup]="form">
   <!-- ...more form controls... -->

   <div class="form-group" formGroupName="myCheckboxGroup">
      <div class="custom-control custom-checkbox">
        <input type="checkbox" class="custom-control-input" formControlName="myCheckbox1" id="myCheckbox1">
        <label class="custom-control-label" for="myCheckbox1">Check</label>
      </div>

      <div class="custom-control custom-checkbox">
        <input type="checkbox" class="custom-control-input" formControlName="myCheckbox2" id="myCheckbox2">
        <label class="custom-control-label" for="myCheckbox2">At least</label>
      </div>

      <div class="custom-control custom-checkbox">
        <input type="checkbox" class="custom-control-input" formControlName="myCheckbox3" id="myCheckbox3">
        <label class="custom-control-label" for="myCheckbox3">One</label>
      </div>

      <div class="invalid-feedback" *ngIf="form.controls['myCheckboxGroup'].errors && form.controls['myCheckboxGroup'].errors.requireCheckboxesToBeChecked">At least one checkbox is required to check</div>
    </div>

    <!-- ...more form controls... -->
  </ng-container>

*This template is very static. Of course you could create it dynamically by using an additional array that holds the the form-data(key of FormControl, label, required, etc.) and create the template automatically by use of ngFor.

Please don't abuse hidden FormControl's like in the accepted answer. A FormControl is not meant to store data like id, label, help-text etc. and doesnt even have a name/key. All this, and much more, should be stored separate, e.g. by a regular array of objects. A FormControl only holds an input-value and provides all this cool state's and functions.

I created a working example you can play with: https://stackblitz.com/edit/angular-at-least-one-checkbox-checked

Validating that at least one checkbox is checked., How to limit checkbox should select only 15 out of 300 and if they try to select more //This will check that at least one checkbox is checked  At least one checkbox must be selected (checked) 1 minute read There is a form with multiple checkboxes and we’re going to make sure that at least one is checked using pure JavaScript.

On validation (i.e for example some click event) iterate over your array and check whether at least one item is true.

let isSelected: any = this.officeLIST.filter((item) => item.checked === true);
if(isSelected != null && isSelected.length > 0) {
 //At least one is selected
}else {
 alert("select at least one");
}

How to check atleast one ChcekBox is selected or not using , I would like to show an alert if no check box was checked in a field. The idea is that at least one check box should be checked. I have an onSubmit for the form  Here Mudassar Ahmed Khan has explained how to validate ASP.Net CheckBoxList control using Custom Validator and perform at least one CheckBox Checked Validation in it. The ASP.Net Custom Validator will make use of JavaScript function to validate the CheckBoxList control.

I had the same problem and this is the solution I ended up using with Angular 6 FormGroup because I had few checkboxes.

HTML Note: I'm using Angular Material for styling, change as needed.

<form [formGroup]="form">
  <mat-checkbox formControlName="checkbox1">First Checkbox</mat-checkbox>
  <mat-checkbox formControlName="checkbox2">Second Checkbox</mat-checkbox>
  <mat-checkbox formControlName="checkbox3">Third Checkbox</mat-checkbox>
</form>

TypeScript

form: FormGroup;

constructor(private formBuilder: FormBuilder){}

ngOnInit(){

  this.form = this.formBuilder.group({
    checkbox1: [''],
    checkbox2: [''],
    checkbox3: [''],
  });

  this.form.setErrors({required: true});
  this.form.valueChanges.subscribe((newValue) => {
    if (newValue.checkbox1 === true || newValue.checkbox2 === true || newValue.checkbox3 === true) {
      this.form.setErrors(null);
    } else {
      this.form.setErrors({required: true});
    }
  });
}

Basically, subscribe to any changes in the form and then modify the errors as needed according to the new form values.

Only submit if at least one checkbox is checked, attr() for the disabled attribute with that boolean value will enable/disable that button. var checkboxes = $("input[type='checkbox']"), submitButt = $(  Questions: I’m trying to validate a form using the validate plugin for jquery. I want to require that the user check at least one checkbox in a group in order for the form to be submitted.

Add (ngModelChange)="onChange(officeLIST)" to your checkbox and have below code in your .ts file.

onChange(items) {
    var found = items.find(function (x) { return x.checked === true; });
    if (found)
      this.isChecked = true;
    else
      this.isChecked = false;
  }

Use isChecked variable any places you want.

Test if at least one checkbox is checked, Submit Form if At Least One Checkbox is Checked will not be submitted, User will be required to check at least one checkbox to submit form. With reactive forms the best, easiest and probably right way is to use a FormGroup that holds your grouped checkboxes and create a validator to check if at least one(or more) checkbox is checked within that group. To do so just create another FormGroup inside your existing FormGroup and attach a validator to it:

Submit Form if At Least One Checkbox is Checked, I have a form in which the user should at least select one of the check boxes. This is the code for generating a group of check boxes in the view:  Within the function it is checked whether the checkbox is same on which the function should work. The approach will work on n number of checkbox too. One enhancement that can be done is to find only the checkboxes of interest through javascript. So overhead of looking in entire list is saved.

How to validate that at least one checkbox is checked in a form , <input type="checkbox" name="sel[]" value="1" id="sel"> I want to I want to create a javascript function that checks to make sure at least one is selected, if not length of the array to loop through and check each item if checked. Each and every id must be unique; no two elements can share them. Demo Download. Today in this tutorial i will going to explain how to restrict form submission if at least one checkbox is not checked, when a user press submit button an alert will appear to check at least one checkbox if at least one checkbox is not checked it means form will not be submitted, User will be required to check at least one checkbox to submit form.

Checking if at east 1 checkbox is selected in an array of checkboxes , I'm trying to ensure that at least one checkbox is selected. I'm using the query validate plugin. here is the checkbox html <!-- Checkbox None of your checkboxes have a class-attribute “select”, so you should add that to your checkboxes.

Comments
  • you are not using any form tags, by validation when you want to validate? like on click of some button should say nothing selected
  • I want to validate when there is no single checkbox is checked. for eg: name: textbox, when user clicked on it but did not enter anything then, should display'name is required'. same goes to checkbox
  • Please reconsider choosing @Mick answer as the accepted answer.
  • Better answer IMHO
  • Hi thanks for this answer, but I'm just curious - is it necessary to instantiate 3 FormControls for every checkbox in order to create a "required" validateable (dont think thats a word) checkbox list? This definitely seems to work and I'm going to mess with it a little bit, but I feel like there's some unnecessary overhead here... what do you think?
  • @AdamPlocher Sorry for incorrect response before, I was able to think about your question right now. The reason for 3 instance per checkbox here is that FormControl itself doesn't support for keeping additional info such as id and text for the checkbox.
  • @AdamPlocher You should not abuse a FormControl to store data as their value(here the key and label). Thats a very wrong way to think about reactive forms in Angular. A FormGroup holds FormControls with their validators, current value and current status and nothing more. This is not a good answer. The general idea of creating an additonal, hidden, checkbox (Step2) is not too bad tho, but it is way easier to create a validator for the whole FormGroup. No need to watch valueChanges. Also btw. having it required is wrong it should have the validator requiredTrue.
  • Please see my answer for that solution
  • one thing: { validators: requireCheckboxesToBeCheckedValidator() } - the rest is ok
  • @Sergej FormGroup constructor accepts ValidatorFn or ValidatorFn[]. Or what do you mean?
  • I mean that the validators must be an object with the validators key. You have missed it in your example. The 2nd argument in the FormGroup construcor. angular.io/api/forms/FormGroup You must be mixed up it with the FormControl which takes the validator itself as a parameter.