4

I have a Spring Mvc 3 form that POST to a controller, in the controller i make calls to execute DML statements. I also have a separate validation class that implements Validator and is called in my Controller. I do both simple and complex validation in there like check if user name exist and return an error message if it exist.

I would like to use ajax to validate only the user name field when i tab out of the field on the view, but i would like to make a call to the already implemented validation i have and only validate the username field.

How can i achieve this, will i need to make a call in Ajax to the Controller class and have a separate @RequestMapping to handle this only? Can i have an example om how this should be implemented.

devdar
  • 5,564
  • 28
  • 100
  • 153

1 Answers1

1

//add this on the controller side

if(result.hasErrors() ){
        for (Object object : result.getAllErrors()) {
            if(object instanceof FieldError) {
                FieldError fieldError = (FieldError) object;
                String message = messageSource.getMessage(fieldError, null);
                logger.info("Error : " +  message + " - "  + fieldError.getField());
                errors.add(fieldError.getField() + "#" + message);
            }
        }
        response.setStatus("FAIL");
        response.setResult(errors);

after the ajax response , set error on respective result fields

$.each(response.result, function(index, errorString){

                     var array = errorString.split("#");
                     $('[for="' +array[0]+ '"]').html(array[1]);
                 });
jaskirat Singh
  • 696
  • 1
  • 8
  • 17