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.

1
  • 1
    Yes, a separate method in the Controller annotated with @RequestMapping sounds like the most straightforward solution. Commented Sep 16, 2012 at 22:55

1 Answer 1

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]);
                 });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.