michael michael - 1 year ago 159
AngularJS Question

AngularJS: list all form errors

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

to do so; yet I don't fully get it working.

If validation errors occur inside a
, e.g.:

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

Empty values result in
containing the following:

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

On the other hand, if validation errors occur outside this

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

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:

Answer Source

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.

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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download