Reputation: 1071
The code below is my attempt to validate a list of values in a form. The values are in a table within an ng-repeat
directive and should be validated as required. Any inputs will be appreciated.
<form name="form1">
<table>
<tr ng-repeat="param in params">
<td>
{{param.name}}
</td>
<td>
<input name="i{{$index}}" ng-model="param.val" required />
<span style="color:red" ng-show="form1.i{{$index}}.$dirty && form1.i{{$index}}.$invalid">
<span ng-show="form1.i{{$index}}.required">This field is required</span>
</span>
</td>
</tr>
</table>
</form>
Upvotes: 4
Views: 6921
Reputation: 764
<form name="form1" ng-controller="mycontroller">
<table>
<tbody>
<tr ng-repeat="param in params">
<td>{{param.name}}</td>
<td>
<input name="i{{$index}}" ng-model="param.val" required="" />
<span style="color:red" ng-show="form1.['i{{$index}}'].$dirty && form1.['i{{$index}}'].$invalid">
<span ng-show="form1.['i{{$index}}'].required">This field is required</span>
</span>
</td>
</tr>
</tbody>
</table>
</form>
Working sample: http://plnkr.co/edit/pxtnW5vzWP8J4KYno3jN?p=preview
Upvotes: 3
Reputation: 49590
I think @SunilD'2 comment to another answer is worth an answer of its own, because the approach with ng-form
can facilitate more validation scenarios (for example, highlighting a row in the table where one of the inputs is invalid)
<form name="form1">
<table>
<tr ng-repeat="param in params">
<td>
{{param.name}}
</td>
<td ng-form="cellForm">
<input ng-model="param.val" required />
<span ng-show="cellForm.$dirty && cellForm.$invalid">
<span ng-show="cellForm.$error.required">This field is required</span>
</span>
</td>
</tr>
</table>
</form>
Validity of nested ng-form
sets the validity of their parent form.
Upvotes: 4