java Spring Boot web应用程序如何验证另一个字段所需的表单字段?
我有一个Spring Boot web应用程序,其中表单支持bean的字段用Bean Validation注释进行注释(请参见Baeldung's tutorial或the docs at spring.io)。例如,Customer Bean上的字段可能注释如下:
@NotBlank
@Pattern(regexp="[ \\.A-Za-z-]*")
private String firstName;
@DateTimeFormat(pattern="M/d/yyyy")
@NotNull
@Past
private Date DOB;
我想知道的是:(如何)实现一个查看多个字段的复杂验证我的意思是,使用这个框架。例如,假设我有一个字段Country
和一个字段ZipCode
,我希望ZipCode
是@NotBlank
当且仅当Country
等于"US"
,否则可选
在我的控制器中,使用@Valid
注释可以非常优雅地触发验证,错误会附加到BindingResult
对象。就像这样:
@PostMapping("customer/{id}")
public String updateCustomer( @PathVariable("id") Integer id,
@Valid @ModelAttribute("form") CustomerForm form,
BindingResult bindingResult ) {
if (bindingResult.hasErrors()) {
return "customerview";
}
customerService.updateCustomer(form);
return "redirect:/customer/"+id;
}
我希望找到一种方法来编写这个条件验证器,它也会被@Valid
注释触发,并将其错误消息附加到BindingResult
中的ZipCode
字段。理想情况下,我根本不需要更改控制器代码
# 1 楼答案
对于这类东西,你需要使用跨域验证。请尝试:
创建注释:
创建自定义验证程序:
为你的班级做注解:
除了现有的字段验证器之外,还将处理此类验证