I have a Spring Boot web app in which fields of my form-backing bean are annotated with Bean Validation annotations (see Baeldung's tutorial or the docs at spring.io). For example, fields on Customer beans might be annotated like this:
@NotBlank
@Pattern(regexp="[ \\.A-Za-z-]*")
private String firstName;
@DateTimeFormat(pattern="M/d/yyyy")
@NotNull
@Past
private Date DOB;
What I want to know is: (How) Can I implement a complex validation that looks at multiple fields? I mean, using this framework. For example, let's say I have a field Country
and a field ZipCode
and I want the ZipCode
to be @NotBlank
if and only if the Country
equals "US"
, optional otherwise.
In my Controller, the validation is very elegantly triggered with the use of the @Valid
annotation, and errors are attached to a BindingResult
object. Like so:
@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;
}
What I'm hoping to find is a way to write this conditional validator in a way that it, too, will be triggered by the @Valid
annotation and will attach it's error message to the ZipCode
field in the BindingResult
. Ideally I shouldn't have to change the Controller code at all.