How to require at least 1 checkbox for AngularJS Form Validation?

All we need is an easy explanation of the problem, so here it is.

I have an array of JSON objects which is displayed in a form. I would like to have the form validation work where a user has to select at least one checkbox for the entire form to be valid.

I know that the ng-required can be used but with the implementation I have, it means that all of them have to be selected for it to be valid.

Here is the code I have so far:

index.html:

<div ng-repeat="item in volunteerOptions">
    <label class="checkbox"><input type="checkbox" value="" data-ng-model="item.selected" ng-required="true">{{ item.content }}</label>
</div>

<button type="submit" class="btn btn-success" ng-disabled="!memberRegistrationForm.$valid">Submit</button>

controller.js

$scope.volunteerOptions = [
        { content : 'Content 1', selected : false },
        { content : 'Content 2', selected : false },
        { content : 'Content 3', selected : false },
        { content : 'Content 4', selected : false },
];

Any ideas on how I would be able to achieve this behaviour?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You can add another scope property and use array.some to check if any of the selected are true. Then feed that scope property to ng-required. Something like

$scope.isOptionsRequired = function(){
  return !$scope.volunteerOptions.some(function(options){
    return options.selected;
  });
}

<input type="checkbox" value="" data-ng-model="item.selected" ng-required="isOptionsRequired()">

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply