Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: How to validate ng-repeat form fields

Tags:

angularjs

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>
like image 799
ps0604 Avatar asked Mar 18 '23 02:03

ps0604


1 Answers

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

like image 121
New Dev Avatar answered Mar 31 '23 21:03

New Dev