0

Lets say I have table with 10 rows and in each row 10 columns of checkboxes

before the user submits I want to add the following validation: in each row at least two checkbox are checked!

<form name="myForm">
    <div data-ng-controller="myController">
        <table border="1">
            <tr>
                <td><input type="checkbox" /></td>
                <td><input type="checkbox" /></td>
                <td><input type="checkbox" /></td>
                <td><input type="checkbox" /></td>
                <td><input type="checkbox" /></td>
                <td><input type="checkbox" /></td>
                <td><input type="checkbox" /></td>
                <td><input type="checkbox" /></td>
                <td><input type="checkbox" /></td>
                <td><input type="checkbox" /></td>
            </tr>
            ...
        </table>

        <button data-ng-click="save()" ng-disabled="$myForm.invalid">Save</button>
</form>


$scope.save = function() {
    if (myForm.$valid){
        alert("can submit the form...")
    }
};

How to do this? where to add the validation functionality?

2 Answers 2

2

I recently answered a similar question with a custom directive that allows the user to define groups of controls (text-fields, selects, checkboxs, whatever) and require that at least one control in each group not empty.

It should be easy to modify so that at least two controls are not empty.
Then myForm.$valid will always be "up-to-date" (so you can use it to give visual feedback or allow the form to be submitted).

Sign up to request clarification or add additional context in comments.

2 Comments

This is exactly what I was looking for,, a bit long but I think is how it should be in Angular platform.. thanks!
Yeah, the implementation is a bit long (not much though), but the functionality added is not trivial. Besides, you only include it once in the project and then it can be integrated in any view with no extra code (neither in the controller nor in the view) :)
1

If your checkboxes are static in the HTML, You can bind the checkboxes to boolean models like:

<input type="checkbox" ng-model="checked[1]">
<a href="javascript:;" data-ng-click="validate()">Validate</a>

and then use something like this to validate

$scope.checked = {};
$scope.validate = function() {
  var count=0;
  angular.forEach($scope.checked, function(k,v){ if (k) count++; });
  if (count > 2)
      alert("validated");
};      

To extend this to multiple rows is trivial.

You can see this working on here: http://plnkr.co/edit/thbJ81KWUDyF6WTcWL9u?p=preview

Of course you can define an array in the controller and use the ng-repeat directive in conjunction with this idea.

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.