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?

limsha
  • 128
  • 6
john Smith
  • 1,565
  • 7
  • 34
  • 54

2 Answers2

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).

Community
  • 1
  • 1
gkalpak
  • 47,844
  • 8
  • 105
  • 118
  • This is exactly what I was looking for,, a bit long but I think is how it should be in Angular platform.. thanks! – john Smith Jun 22 '14 at 11:22
  • 1
    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) :) – gkalpak Jun 22 '14 at 11:27
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.

Alfonso Embid-Desmet
  • 3,561
  • 3
  • 32
  • 45