Search code examples
angularjsangularjs-directiveangularjs-scopeangularjs-validation

How can i count the number of errors on Form?


FIDDLE

How can i count the number of errors made on form ?

HTML

 <div ng-show="form.$submitted && form.$invalid">
      Sorry but 3 errors have been made.
 </div>

Solution

  • One way you could do this by using the specific count of a specific error criteria, required, pattern etc.. that are available as a part of form's $error[prop] array. In your case you could try using form.$error.required.length:-

    <div ng-show="form.$submitted && form.$invalid">
           Sorry but {{form.$error.required.length}} errors have been made.
    </div>
    

    Demo

    You could add a function on the controller which can determine the number of errors on the form and return it, and use it in the view to display the total error count.

     $scope.numberoferrors=function(form){
        var count = 0,
            errors = form.$error;
    
         angular.forEach(errors, function(val){ if(angular.isArray(val)) {  count += val.length; }  });
        //Object.keys(errors).forEach(function(key){ count += errors[key].length  }); //get count of all error categories from form
    
        return count;
     };
    

    Demo