NoobDeveloper NoobDeveloper - 4 months ago 58
AngularJS Question

How do you show validation errors returned from WebAPI?

I am using latest version of angular.js and WebAPI & bootstrap.

Imagine a form with few textboxes & submit button. Once a user submits the form, data is validated by WebAPI call on server as we cant trust client side validations.

In API controller, we do all our business validations.
Assuming that data entered in all the textboxes are invalid:


  1. How should i return error message from my WebAPI so that the form displays it properly ?

    In normal MVC way without angular, this is easy. We can add errors to ModelState and the view will pick it and show the errors properly.


Answer

AngularJS has built in form validation:

WebApi

You can return errors in whatever format you want. I would recommend that the response should contain following information:

  • An error message describing the error
  • In which part of the request the error occured (Payload, url params, query params)
  • Which attribute triggered the error (email, password, ...)
  • The response should also have the correct error status code (400, 401, ...)

Client

Assume that your response looks like this:

{
    "message": "Email is invalid",
    "area": "payload",
    "field": "email"
}

Create your form and make sure the name attribute is assigned, since in your form validation you will need the it. By now angular will append form validations states to your elements:

<input type="email" name="email" id="email" ng-model="user.email" ng-minlength="6" required />

You can now dynamically display error messages by accessing the validation fields:

<span ng-show="form.email.$error.required && form.email.$dirty">Email can not be empty</span>