0

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?

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.