Reputation: 1605
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?
Upvotes: 0
Views: 118
Reputation: 3632
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.
Upvotes: 1
Reputation: 48211
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).
Upvotes: 2