Reputation: 3964
Using AngularJS, I want to establish a validation rule where at least 2 check boxes must be checked for the input to be considered valid. I have tried this:
<div ng-repeat="item in items">
<label><input type="checkbox" ng-model="checked[item.id]" ng-required="!isChecked" />
<span>{{item.title}}</span></label>
</div>
and
// checkbox validation
angular.module('app', []).
run(function($rootScope) {
$rootScope.items = [
{ id: 1, title: 'Certified Plumber' },
{ id: 2, title: 'Carpentry Experience' },
{ id: 3, title: 'Certified Electrician' },
{ id: 4, title: 'Bartending Experience' },
{ id: 5, title: 'Food Hygiene Certificate' },
{ id: 6, title: 'First Aid Course' },
{ id: 7, title: 'Forklift Drive Certificate' },
{ id: 8, title: "Driver's License (Type B)" }
];
$rootScope.checked = {};
$rootScope.isChecked = false;
$rootScope.$watch('checked', function(selected) {
$rootScope.isChecked = false;
angular.forEach(selected, function(isChecked) {
if (isChecked) $rootScope.isChecked = true;
});
}, true);
});
Now the validation is working when at least one checkbox is checked. How do I customize it for at least two checkboxes?
Upvotes: 0
Views: 142
Reputation: 1672
How about something like:
$rootScope.isChecked = false;
$rootScope.$watch('checked', function(selected) {
$rootScope.isChecked = false;
$rootScope.checkedCounter = 0;
angular.forEach(selected, function(isChecked) {
if (isChecked) $rootScope.checkedCounter = $rootScope.checkedCounter + 1;
if($rootScope.checkedCounter >= 2) $rootScope.isChecked = true;
});
}, true);
Upvotes: 1