What is the correct way to validate all form fields on submit when using ng-repeat for dynamic form?

Issue

I have a form with some fields (build with ng-repeat, so I dont know how much). I added to the submit button

ng-disabled=form.field.$invalid

and added to all the fields “required” but the ng-disabled work just for this last field. my code:

 <form name="form" novalidate>

            <div ng-repeat="q in questions">
                 <textarea name="answer" type="text"  ng-model="answers[$index]" required></textarea>


            </div>
            <button ng-disabled="form.answer.$invalid || form.answer.$pristine" type="submit" ng-click="submit(q)">'Submit'</button>
        </form>

how can I validate the user change all fields? thanks!

Solution

That is because all your inputs have the same name, hence the behavior due to the form controller instance will have just one property with the name answers and it will point to the last ng-model with that name in the form. Instead provide different names for your inputs using ng-attr-name with probably appending $index and use $invalid property of the form, form will be invalid as long as one of the ng-model(s) (with constraints) within the form is invalid. So just disable the button until the form is invalid since it is a catch-all property on the form controller.

<div ng-repeat="q in questions">
  <!-- Provide dynamic form names -->
  <textarea ng-attr-name="answer{{$index}}" type="text" 
            ng-model="answers[$index]" required></textarea>
 </div>
 <!-- Use form.$invalid -->
 <button ng-disabled="form.$invalid || form.$pristine"  
         type="submit" ng-click="submit(q)">Submit</button>
angular.module('app', []).controller('ctrl', function($scope) {
  $scope.questions = ["q1", "q2"]
  $scope.answers = {};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">

  <form name="form" novalidate>

    <div ng-repeat="q in questions">
      <textarea ng-attr-name="answer{{$index}}" type="text" ng-model="answers[$index]" required></textarea>


    </div>
    <button ng-disabled="form.$invalid || form.$pristine" type="submit" ng-click="submit(q)">Submit</button>
  </form>
</div>

Answered By – PSL

Answer Checked By – Robin (AngularFixing Admin)

Leave a Reply

Your email address will not be published.