简体   繁体   中英

Spring bean validation without using @valid

I have used spring validation in the conventional way like this:

@RequestMapping(value="userRegistration", method = RequestMethod.POST)
public ModelAndView registerUser(@Valid UserAccountVO userAccountVO, BindingResult result,Model model){
    if (result.hasErrors()){
    // Do something
    }
//Do something else
}

That works well and good.

But now I have case where I can't do a form submission, but instead get values in javascript and send them using Ajax on click of a button, something like this.

var nameStr = $("#usrnmbx").val();
var emailidStr = $("#emailidbx").val()
//and more and then send them using ajax

So to implement bean validation my new method looks something like this.

@RequestMapping(value = "/userRegistration", method = RequestMethod.POST)
public @ResponseBody JSONresponse registerUser(HttpServletRequest request,@RequestParam(value = "name") String name, // and more){

UserAccountVO userAccountVO = new UserAccountVO(name, emailId,password, confirmPassword);
BindingResult result = new BeanPropertyBindingResult(userAccountVO,"userAccount");
userAccountValidator.validate(userAccountVO, result); //userAccountValidator is spring Validator implementation 
if (result.hasErrors()) {
 //Do something
}
//Do something else
}

But this looks dirty. I definitely think there are better ways of doing this. And this doesn't seem like picking up the validation annotations that I have put up in the POJO. Can any of you suggest a better implementation. Thanks in advance.

you can submit whole form with ajax. In this case your command object should be populated as ordinary form submission.

here is my aproach

        function submitAjaxForm(form, url) {  
        $.post(url, $(form).serialize(),function(data) {
              ...........
            }); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM