Angularjs checkboxlist required validation with demo

how to require at least 1 checkbox for angularjs form validation angular checkbox required validation at least one checkbox checked validation in angularjs check if checkbox is checked angularjs angular2 checkbox group validation ng messages checkbox angular form require checkbox check if atleast one checkbox is checked angularjs

Checkbox list at least one is required, checkbox list minimum 3 is required, gender at least one is required are the basic requirement for any situation. We will use the toggle trick to add remove the selected items from the list of checkbox values.

In this article we are going to see the examples:

1- Radiobutton list, at least one value is required 2- Checkbox list, at least one value is required 3- Checkbox list, at least three value is required 4- Checkbox list select all 5- Checkbox list clear all 6- Clear all checkbox on un-check of any checkbox

Gender Radio button list Simplest example of gender selection to select one of gender and make required until user select any one of gender:

<div>
  <label><input type="radio" 
    name= "gender" 
    value="Male" 
    ng-model="gender" 
    required /> Male</label>
</div>
<div>
  <label><input type="radio" 
    name= "gender" 
    value="Female" 
    ng-model="gender" 
    required  /> Female</label>
</div>
  • name: We used here name to group the radio buttons to select only one item from group.
  • value: every radio button will have unique value
  • ng-model: it will be assigned on click/switching
  • required: we can use either required or ng-required= "true"

Next we will use the check box list but the problem is, we cannot directly use above trick because in checkbox list we can select multiple items.

At least one checkbox in ng-repeat is required: Here we are going to use the trick toggling, means by default we will have a variable on scope to keep selected items as an array, either blank fir first time or some items in it in edit mode. On clicking any check box we will try to find the index of clicked item in selected array, if not exist then we add it otherwise we will remove it from the selected list. Let's see the code and then we can explain in detail:

In controller we have two variables on scope

$scope.selectedAnimals = [];
$scope.animals = ['Cat', 'Bear', 'Deer', 'Lion', 'Tiger'];

Now we need to create the list by using ng-repeat on animals, here is the HTML

<ul  class="list-group">
  <li ng-repeat='animal in animals' class="list-group-item">
    <label>
      <input type="checkbox"
        ng-model="xyx"
        ng-click="toggleAnimal(animal)"
        ng-checked="selectedAnimals.indexOf(animal) > -1"
        ng-required="selectedAnimals.length == 0" /> 
        {{animal}}</label>
  </li>                  
</ul>
  • ngRepeat: Simply create the list of items
  • ngModel: it is required for ng-required so give any name, it is only to stop the error that ng-required need the ng-model
  • ngClick: this is the method we will use to add or remove the item from the selected list which we will see next
  • ngChecked: Item will be check or un-checked on the basis of selected list
  • ngRequired: if selected items count is 0 means no item is selected yet and it is required

Let's add the method chkSelectAnimals(animal)

$scope.toggleAnimal = function(animal){
    var index = $scope.selectedAnimals.indexOf(animal);
    if(index == -1) {
      $scope.selectedAnimals.push(animal);
    }
    else{
      $scope.selectedAnimals.splice(index, 1);
    }
}

This function accept a value, clicked item, in our case animal name, check the index of this item in selected list, if exist (greater than -1), remove it otherwise add to the list.

Checkbox list minimum 3 items are required, Select All Checkbox:

In this section we are going to see how to make N-number of items required, how we can use select all, clear all and on checking and unchecking items how we manage select all checkbox, say if all items selected one by one then all checkbox should be selected, on unchecking a checkbox, all checkbox should be un-checked.

Here we also use a list of color object and keep id of object on selection:

$scope.selectedColors = [];
$scope.colors = [
  {"id": 1, "color": "Red"},
  {"id": 2, "color": "Orange"},
  {"id": 3, "color": "Yellow"},
  {"id": 4, "color": "Green"},
  {"id": 5, "color": "Cyan"},
  {"id": 6, "color": "Blue"},
  {"id": 7, "color": "Indigo"}
];

Let's add HTML for "Select/Clear All" check box and checkbox list of colors from the above array we created, see this time we are using the array of object of colors and we will create the list of ids:

<label>
  <input type="checkbox" 
    ng-model="chkAll"
    ng-checked="colors.length === selectedColors.length"
    ng-click="selectAllColors()" > Select/Clear All</label>

<ul class="list-group">
 <li class="list-group-item" ng-repeat="item in colors">
   <label> 
     <input type="checkbox"
        ng-model="xyz"
        ng-checked="selectedColors.indexOf(item.id) > -1"
        ng-click="toggleColor(item.id)"
        ng-required="selectedColors.length < 3"> {{item.color}}</label> 
 </li>
</ul>

Select/Clear All: trick is simple, if all selected item count became equal to the list of colors (source list) items count, it will be checked otherwise un-checked by using the code ng-checked="colors.length === selectedColors.length". On clicking it, if checkbox is checked we select all otherwise clear the array, see this:

$scope.selectAllColors = function(){   
    if($scope.chkAll == true)
       $scope.selectedColors = $scope.colors.map(x=>x.id)
    else
      $scope.selectedColors = [];
}
// if you don't want to use the arrow function then use function like this
$scope.colors.map( function(x) {return x.id; })

Creating the list of checkbox is very same as our previous example except the number of required item are 3 now so ng-required="selectedColors.length < 3", means the number of selected item must be 3. See the rest of the code:

$scope.toggleColor = function(id){
   var index = $scope.selectedColors.indexOf(id);
   if(index == -1)
     $scope.selectedColors.push(id);
   else
     $scope.selectedColors.splice(index, 1);
}

We would love to help if you have any special case which can help others as well.

Ali Adravi Having 13+ years of experience in Microsoft Technologies (C#, ASP.Net, MVC and SQL Server). Worked with Metaoption LLC, for more than 9 years and still with the same company. Always ready to learn new technologies and tricks.
  • angularjs
  • checkbox-list
By Ali Adravi On 22 Oct, 17  Viewed: 78

Other blogs you may like

Angularjs powerful paging on table and searching with delay and demo

Paging on table is the basic requirement and most of us look for some grid so it can provide the complete feature of paging and sorting but in Angularjs it is so easy that anyone can achieve it by writing some code. I checked and found most of the available code give the paging feature in for 1 to... By Ali Adravi   On 14 Aug 2015  Viewed: 10,099

Angularjs Cascading Dropdown/Select with demo

Cascading dropdown with angularjs is easier than MVC and ASP.Net. In Angularjs ng-change is the best event to hook the function to get the second dropdown list items. In this article, we will try to fill the state dropdown on selection change of country and then fill the city dropdown on change... By Ali Adravi   On 06 Aug 2015  Viewed: 39,381

Angularjs CRUD with Web API, Entity Framework & Bootstrap modal popup part 2

Add/Edid Customer in Modal Popup --- In previous article we discussed how to search, delete and show detail of customer and contact list. In this article we will try to open the modal popup to add new customer and edit an existing customer record. I divided article in two parts because of the... By Ali Adravi   On 29 Jul 2015  Viewed: 15,001

Custom Directives in AngularJS with example and demo

Angularjs custom directives are the common to avoid the duplicate code, it is easy powerful and really nice. There are already too many directive have been created by experts but as a developer we need to write our own to achieve our specific goal. ng-model, ng-if, ng-show, ng-repeat all these are... By Ali Adravi   On 29 Jul 2015  Viewed: 3,032

Angularjs CRUD with Web API, Entity Framework & Bootstrap modal popup part 1

Search sort Insert update and delete are the basic features we need to learn first to learn any language, In this article we will try to create these features with Web API, bootstrap modal popup and ui.router. We will use enetity framework code first to save and retrieve data from database. We... By Ali Adravi   On 28 Jul 2015  Viewed: 26,007