Lets say, I have below bean that I get in my Controller's entry method using @RequestBody
public class MyRequestBean extends RequestBean {
private static final long serialVersionUID = 1L;
private String lastName ;
private String firstName ;
private String ssnNumber;
private String groupCd;
}
I have put @Valid
at entry point method beside - @RequestBody
.
I am trying to achieve two things,
ssnNumber
is an absolute mandatory field - if its empty or null - no need to validate anything else. Just return the error message.
If ssnNumber
is valid , see if any of the three fields - firstName
, lastName
and groupCd
are valid with @NotNull
& @NotEmpty
. If any of the fields are present, handle the request.
How can I achieve this?
I am using these two dependencies for validation purpose ,
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
Validation API is - 1.1.0.Final & Hibernate Validator is - 5.3.4.Final
EDIT: Possible duplicate link is talking about JSON field order. In my case, field order doesn't matter. Its about field validation order. Am I missing something?
I didn't found a way to do it with annotations i.e. order field validations with annotations.
I had to eventually write my custom validator class- MyValidator
by implementing - org.springframework.validation.Validator
and writing my ordered logic there and then adding that validator for that controller in controller class,
@InitBinder
public void globalInitBinder(WebDataBinder binder) {
binder.addValidators(new MyValidator());
}