Conditional validation in spring mvc

China☆狼群 提交于 2019-12-25 02:53:27

问题


Now I have following controller method signature:

@ResponseBody
    @RequestMapping(value = "/member/createCompany/addParams", method = RequestMethod.POST)
    public ResponseEntity setCompanyParams(
            @RequestParam("companyName") String companyName,
            @RequestParam("email") String email,               
            HttpSession session, Principal principal) throws Exception {...}

I need to add validation for input parameters. Now I am going to create object like this:

class MyDto{
    @NotEmpty            
    String companyName;
    @Email // should be checked only if principal == null
    String email;   
}

and I am going to write something like this:

@ResponseBody
@RequestMapping(value = "/member/createCompany/addParams", method = RequestMethod.POST)
public ResponseEntity setCompanyParams( MyDto myDto, Principal principal) {
    if(principal == null){
        validateOnlyCompanyName(); 
    }else{
         validateAllFields();
    }
    //add data to model
    //return view with validation errors if exists.
}

can you help to achieve my expectations?


回答1:


That's not the way Spring MVC validations work. The validator will validate all the fields and will put its results in a BindingResult object.

But then, it's up to you to do a special processing when principal is null and in that case look as the validation of field companyName :

@ResponseBody
@RequestMapping(value = "/member/createCompany/addParams", method = RequestMethod.POST)
public ResponseEntity setCompanyParams(@ModelAttribute MyDto myDto, BindingResult result,
        Principal principal) {
    if(principal == null){
        if (result.hasFieldErrors("companyName")) {
            // ... process errors on companyName Fields
        } 
    }else{
         if (result.hasErrors()) { // test any error
             // ... process any field error
         }
    }
    //add data to model
    //return view with validation errors if exists.
}


来源:https://stackoverflow.com/questions/29607563/conditional-validation-in-spring-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!