ps0604 ps0604 - 2 months ago 21
AngularJS Question

AngularJS: How to validate ng-repeat form fields

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>

Answer

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.

plunker