从bindingResult验证中忽略字段

时间:2019-06-13 15:21:28

标签: spring-boot spring-validator

我正在使用removeAll + checklistItem.forEach { $0.checklistItems.removeAll { !$0.showTrailer || $0.showVehicle } } checklistItem.removeAll { $0.count == 0 } + SpringBoot 2.1.3 (Embedded Tomcat)。我在验证Thymeleaf 3时遇到问题,类似于以下问题:

java 8

UserDTO在数据库内部检查电子邮件是否存在(只允许接收一封用于帐户的电子邮件)。我有2个控制器,一个用于插入用户,另一个用于更新用户

@Data
public class UserDTO {
    @NotNull
    private String name;
    @NotNull
    private String surname;
    .....
    @NotBlank
    @Email
    @UniqueEmailConstraint   // this is a custom validator
    private String email;
    @NotNull
    private String pass;
    .......
}

以及具有其他功能的类似产品:

@UniqueEmailConstraint

问题在于,当我选择一个用户对其进行修改时,将打开一个百里香叶视图,并向我显示按预期插入的所有数据(包括邮件)。如果我尝试修改其他字段,例如@PostMapping("/save-user") String saveUser(@ModelAttribute("userDTO") @Valid UserDto userDto, BindingResult bindingResult, Model model) { if (bindingResult.hasErrors()) { return "fragment/form-user"; } ,然后单击“提交我的控制器”,则会显示错误,因为它在数据库上找到了电子邮件。

问题是,有没有办法忽略@PostMapping("/update-user") String updateUser(@ModelAttribute("userDTO") @Valid UserDto userDto, BindingResult bindingResult, Model model) { if (bindingResult.hasErrors()) { return "fragment/form-user"; } 上的某些字段?因为我想忽略第二个控制器验证上的Address错误。

谢谢

1 个答案:

答案 0 :(得分:0)

我遇到了类似的问题,希望对您有所帮助: 可以说有一个带有两个按钮的员工HTML表单。 其中一个按钮应验证整个表单,另一个按钮应仅验证一个字段,而忽略其余字段的验证。

@RequestMapping(method = RequestMethod.POST, value = "saveEmployee", params = "action=save")
public ModelAndView saveEmployee(@Valid @ModelAttribute("employee") EmployeeDTO employee, BindingResult bindingResult, final HttpServletRequest request, final Model model) {
    ModelAndView mav = new ModelAndView();

    //Create a new BindingResult with zero errors
    BindingResult newBindingResult = new BeanPropertyBindingResult(employee, "employee");

    //Add to the new BindingResult the error which is caused by the field 'employeeNumber'
    newBindingResult.addError(bindingResult.getFieldError("employeeNumber"));
    //If required, more fields can be added to the new BindingResult

    //Check if the new BindingResult contains errors -> only the fields added above.
    if (newBindingResult.hasErrors()) {
        //Do this, if the new BindingResult contains validation errors
    } else {
        //Do that, if the new BindingResult does not contain errors validation errors
        //If your form contains other validation errors for fields other than 'employeeNumber', the validation for them will be ignored.
    }

    //Set the view and return it.
    mav.setViewName(xxx);
    return mav;
}