1

I had a simple register form, and validation worked fine. Something like this:

@RequestMapping(value = "/email", method = RequestMethod.POST)
public String changeEmail(@Valid @ModelAttribute("editEmail") EditEmailForm editEmailForm, BindingResult result) {
    if (result.hasErrors()) {
        return "editAccount";
    }

    userService.changeEmail(editEmailForm);

    return "redirect:/";
}

and @Valid annotation did its job and if there were any errors on my form they were displayed in a correct position on my *.vm view.

But now I would like to use AJAX to send my form, so I changed my Controller to :

@RequestMapping(value = "/email", method = RequestMethod.POST)
@ResponseBody
public String changeEmail(@Valid @ModelAttribute("editEmail") EditEmailForm editEmailForm, BindingResult result) {
    if (result.hasErrors()) {
        return "ERROR";
    }

    userService.changeEmail(editEmailForm);

    return "SUCCESS";
} 

Now I can display the ERROR message if validation fails, but how can I display the same messages as earlier? For example I write a wrong e-mail address, and I would like to see a message that there is a wrong e-mail address. Is it possible to achieve it ?

Thanks

Dawid

Dawid
  • 644
  • 1
  • 14
  • 30

2 Answers2

1

You can return JSON String for your validation response. Let say you have AjaxResponse class

AjaxResponse{
    model; //form attribute
    status;  // OK or ERROR
    description; // message description such as error message
}
Adi Sembiring
  • 5,798
  • 12
  • 58
  • 70
  • ok, that looks like a good solution, but could you write a simple example? I didn't use JSON earlier. how to populate JSON data and display errors on my view file? – Dawid May 27 '11 at 10:01
  • I have code reference about Spring Rest with JSON. Hopefully you can modify according on you needs. https://github.com/bijukunjummen/mvc-samples Tutorial from spring blog: http://blog.springsource.com/2009/03/08/rest-in-spring-3-mvc/ – Adi Sembiring May 27 '11 at 22:26
0

Just do another check on the server side to check for a wrong email address. If the email address is wrong then return something like "BAD_EMAIL", and handle it properly on the client side.

if (/* Email is bad */) {
    return "BAD_EMAIL";
}

On the client side, say you're using dojo,

dojo.xhrPost({
    url : "/email",
    ...various args
    load : function (response, ioArgs) {
        if (response === "BAD_EMAIL") {
            // show bad email message
        }
    }
});
zclark
  • 813
  • 2
  • 10
  • 26