开发者

Spring MVC jQuery remote validation

I am using Spring MVC on the server side, but in one of the pages I decided to create an AJAX validation with jQuery rather than the default Spring validation. Everything works great, except when I have to do a remote validation to check if a "title" already exists in the database. For the javascript I have the following:

var validator = $("form").validate({
    rules: {
        title: {
            minlength: 6,
            required: true,
            remote: {
                url: location.href.substring(0,location.hr开发者_如何学编程ef.lastIndexOf('/'))+"/checkLocalArticleTitle.do",
                type: "GET"
            }
        },
        html: {
            minlength: 50,
            required: true
        }
    },
    messages: {
        title: {
            required: "A title is required.",
            remote: "This title already exists."
        }
    }

});

Then, I use Spring-Json to make this validation and give a response:

@RequestMapping("/checkLocalArticleTitle.do")
public ModelAndView checkLocalArticleTitle(HttpServletRequest request,
    HttpServletResponse response) throws ServletException, IOException {
    Map model = new HashMap();
    String result = "FALSE";
    try{
        String title = request.getParameter("title");
        if(!EJBRequester.articleExists(title)){
            result = "TRUE";
        }
    }catch(Exception e){
        System.err.println("Exception: " + e.getMessage());
    }
    model.put("result",result);
    return new ModelAndView("jsonView", model);
}

However, this does not work and the field "title" is never validated. I think the reason for this is that I am returning an answer in the manner:

{result:"TRUE"}

when in fact, the answer should be:

{"TRUE"}

I don't know how to return a single response like this one using a ModelAndView answer.

Another thing that is not working is the customized message for the "remote" validation:

    messages: {
        title: {
            required: "A title is required.",
            remote: "This title already exists."
        }
    },

The required message works, but not the remote message. I looked around, but I didn't see many people using Spring and jQuery at the same time. At least, not mixing with jQuery remote valdations and Spring-Json. I would appreciate some help here.


I encountered the same problem with you.

and now I do

@RequestMapping(value = "/brand/check/exists", method = RequestMethod.GET)
public void isBrandNameExists(HttpServletResponse response,
        @RequestParam(value = "name", required = false) String name)
        throws IOException {
    response.getWriter().write(
            String.valueOf(Brand.findBrandsByName(name).getResultList()
                    .isEmpty()));
}

May not be a good solution. But anyway, that works out.

If there is a better way, please let me know :)

Update:

In Spring 3.0 we can use @ResponseBody to do this

@RequestMapping(value = "/brand/exists/name", method = RequestMethod.GET)
@ResponseBody
public boolean isBrandNameExists(HttpServletResponse response,
        @RequestParam String name) throws IOException {
    return Brand.findBrandsByName(name).getResultList().isEmpty();
}


Here is another example of Spring MVC jQuery remote validation, to check for user uniqueness. Parameter is passed as json and server returns boolean.

Js:

$('#user-form').validate({ // initialize the plugin
    rules: {
        username: {
            required: true,
            remote: function() {  
                var r = {  
                    url: 'service/validateUsernameUnique',  
                    type: "POST",  
                    contentType: "application/json; charset=utf-8",  
                    dataType: "json",  
                    data: '{"username": "' + $( "#username" ).val() + '"}'
                   }   
                return r;  
              }
        },
     },
    messages: {
        username: {
            remote: jQuery.format("User {0} already exists")
        }
    }
});

Spring controller:

@RequestMapping(value="/AdminUserService/validateUsernameUnique", method = RequestMethod.POST)
public @ResponseBody boolean validateUsernameUnique(@RequestBody Object username) {

    @SuppressWarnings("unchecked")
    String name = ((LinkedHashMap<String, String>)username).get("username");
    return userService.validateUsernameUnique(name);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜