Handle AngularJS Form Errors with Ease

Angular 1.3 is just around the corner and with it comes ngMessages. In a lot of ways, it is good and brings a lot to the table in bringing an alternative way of handling errors in a form.

But it's still not simple enough! And I like simple. I work on all sorts of projects, and while I often like the fine-tuning of error handling that Angular affords me, sometimes, I just need something simpler that Just Works™ with minimal effort and configuration.

That's why I built the Form Errors directive. (Catchy name, eh?) It couldn't be simpler to use and the default configuration works 99% of the time (or at least it does for me).

Let's see it in action

<form name="theForm">
  <input type="text" name="name" ng-model="user.name" required>
  <input type="password" "password" ng-model="user.name" required ng-minlength="8">
  <form-errors></form-errors>
  <button type="submit">Submit</button>
<form>

That's it. Really. By putting <form-errors></form-errors> inside a form, it will display a list errors as we type. We can conditionally show the list if we want (see demo), only after they try to submit it, or we can just show it to them as they type.

In this example, <form-errors></form-errors> would display this markup for this form when it's blank:

<ul class="form-errors">
  <li class="form-error">Name is required.</li>
  <li class="form-error">Password is required.</li>
</ul>

It automagically gets the name to use from the name attribute of the input and humanizes it, meaning it turns camelCase into Camel Case, dash-case into Dash Case and snake_case into Snake Case. You can override this to be anything you want with the nice-name attribute on the input. (See docs for how to do this and also how to display custom messages.)

If you start typing in the Name field in the example above, the Name is required message goes away. If you start typing in the Password field, the message is changed to Password is too short until the password is at least 8 characters long, then that disappears, too.

Ease = Efficiency = Time = Money

This thing really has saved me a lot of time because I can be more efficient about how I do the markup and handle the form errors. It may not be the best UX, but when you're doing a ton of forms with a ton of inputs each, this can save you a lot of time.

You can combine this with the ng-invalid classes Angular adds on inputs to get the best of both worlds: immediately drawing them to the error and displaying a message as to what went wrong, all with the minimal amount of effor.

I hope the directive can help you as much as it's helped me. Check out the project on GitHub.