Mvc – Spring MVC – Handling validation errors using AJAX

ajaxmvcspring-mvcvalidation

I'm new to Spring MVC, hence the question may appear trivial.

I have a login form which is submitted via ajax and in return I receive a ModelAndView (displaying existing list of contacts of the user) from the Controller, which I use to overwrite the existing content – the existing login form HTML upon success. My model object contains the list of validation errors which gets populated if there were errors in my form.

I want to show validation errors in my login form if there are any. How should I go about implementing it – should I send a JSON instead of HTML from the server and construct the page at the client using jQuery templates – or can this be achieved even if the Controller returns a ModelAndView?

I have considered having the login JSP and the contacts JSP combined into one and hide/unhide based on response. I do not want to do this though, as this would only increase the payload to be sent to the client.

I think this is a very common problem so there should already be best practices/design approaches for handling this.

Best Answer

It does make sense to send only JSON to client for a number of reasons:

  1. Less traffic between client and server. If you validate some complex form, you'll need to indicate errors in multiple fields. Instead of sending completely rendered form with these fields hilighted, you can send only JSON with names of fields and fix suggestions (NB: from UX perspective, it's better to tell user how to fix, not just how he is wrong).

  2. Avoid rendering code duplication. If you have anywhere client-side validation, you'll have the client-side rendering of validation errors anyway. To make your application behavior and presentation consistent, it's better if you'll have all rendering code in one place, and because of client-side validation it means - on the client, not on the server.

There are still cases, when you cannot have client-side rendering of UI: when user has disabled JavaScript or has non-standard client software, to name few. The number of such users is very low and, considering your development resource constraints, you may decide to ignore this audience. If you do not, there's common approach (now implemented in Angular2 framework) to have a server-side rendering fallback, where you execute basically the same rendering code on server to return static HTML to client. My advice is to stick to simpler solution and then, when you achieved other goals, think about server-side fallback.