Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: list all form errors

Background: I am currently working on an application with tabs; and I'd like to list the fields / sections that fail validation, to direct the user to look for errors in the right tab.

So I tried to leverage form.$error to do so; yet I don't fully get it working.

If validation errors occur inside a ng-repeat, e.g.:

<div ng-repeat="url in urls" ng-form="form">   <input name="inumber" required ng-model="url" />   <br /> </div> 

Empty values result in form.$error containing the following:

 { "required": [   {     "inumber": {}   },   {     "inumber": {}   } ] }

On the other hand, if validation errors occur outside this ng-repeat:

<input ng-model="name" name="iname" required="true" /> 

The form.$error object contains the following:

{ "required": [ {} ] }

yet, I'd expect the following:

{ "required": [ {'iname': {} } ] }

Any ideas on why the name of the element is missing?

A running plunkr can be found here: http://plnkr.co/x6wQMp

like image 655
michael Avatar asked Mar 11 '14 10:03

michael


People also ask

How do you show errors in AngularJS?

in controller: $scope. errors = []; $scope. hasError = false; $scope.

How do you check whether a form is valid or not in AngularJS?

The form instance can optionally be published into the scope using the name attribute. So to check form validity, you can check value of $scope. yourformname. $valid property of scope.

What is $setValidity in AngularJS?

The $setValidity() function is a built-in AngularJS function that is used to assign a key/value combination that can be used to check the validity of a specific model value. The key in this case is “unique” and the value is either true or false.

What is $dirty in AngularJS?

$dirty means the user has changed the input value, $invalid means the address itself is invalid. Therefore the error is only shown if the user has actively changed the input value to either an empty or invalid value.


1 Answers

As @c0bra pointed out in the comments the form.$error object is populated, it just doesn't like being dumped out as JSON.

Looping through form.$errors and it's nested objects will get the desired result however.

<ul>   <li ng-repeat="(key, errors) in form.$error track by $index"> <strong>{{ key }}</strong> errors     <ul>       <li ng-repeat="e in errors">{{ e.$name }} has an error: <strong>{{ key }}</strong>.</li>     </ul>   </li> </ul> 

All the credit goes to c0bra on this.

Another option is to use one of the solutions from this question to assign unique names to the dynamically created inputs.

like image 184
Brett DeWoody Avatar answered Sep 30 '22 06:09

Brett DeWoody