表单的Hibernate Validator:如何验证非常相似的DTO

时间:2016-07-01 01:20:04

标签: java spring hibernate hibernate-validator

我正在使用Hibernate Validator开发一个Spring应用程序来进行表单验证。我有一个看起来像这样的DTO:

public class RegisterUserDTO {


    @Size(min=3)
    private String inputName;

    @Email
    private String inputEmail;

    @Size(min=3)
    private String inputPassword;

    [...]

}

需要inputPassword的地方。在其他地方,我需要使用相同的输入参数,但验证略有不同:

public class RegisterUserDTO {


    @Size(min=3)
    private String inputName;

    @Email
    private String inputEmail;

    //@Size(min=3)
    private String inputPassword;

    [...]

}

inputPassword不是必需的。

如何在两种情况下使用相同的DTO? 如果这是不可能的,那么解决这种情况最简洁的方法是什么?

PS_以下示例在控制器中使用DTO:

@RequestMapping(value = "/users/add", method = RequestMethod.POST)
public String saveUser(ModelMap model, @Valid RegisterUserDTO registerUserDTO, BindingResult result) {
    String template = "/path/to/addUser";
    if (result.hasErrors()) {
        User user = new User(registerUserDTO.getInputName(), registerUserDTO.getInputPassword(), registerUserDTO.getInputEmail());
        model.addAttribute("user", user);
        model.addAttribute("errors", result.getFieldErrors());
    } else {
        User user = userService.insertUser(registerUserDTO.getInputEmail(), registerUserDTO.getInputName(), registerUserDTO.getInputPassword());
        template = "redirect:/path/to/edit/users/" + user.getId();
    }

    return template;
}

1 个答案:

答案 0 :(得分:0)

其中一个解决方案是:

public class RegisterUserDTO {


    @Size(min=3)
    private String inputName;

    @Email
    private String inputEmail;


    private String inputPassword;


}

控制器:

    @RequestMapping(value = "/users/add", method = RequestMethod.POST)
    public String saveUser(ModelMap model, @Valid RegisterUserDTO registerUserDTO, BindingResult result) {
        String template = "/path/to/addUser";
        if (result.hasErrors()) {
            User user = new User(registerUserDTO.getInputName(), registerUserDTO.getInputPassword(), registerUserDTO.getInputEmail());
            model.addAttribute("user", user);
            model.addAttribute("errors", result.getFieldErrors());
            return template;
        } 
//when inputPassword is required add your test
if(your condition){
        FieldError error = new FieldError("registerUserDTO","inputPassword","Your message...");
        result.addError(error);
        return template;
}
User user = userService.insertUser(registerUserDTO.getInputEmail(), registerUserDTO.getInputName(), registerUserDTO.getInputPassword());
template = "redirect:/path/to/edit/users/" + user.getId();   
return template;
}