I use Spring's @Valid
annotation for validate bean's fields which annotated with javax.constraints
annotations.
But I faced a problem when I need to exclude some fields from validation (only for some cases).
I did an investigation didn't found any usefull ways and most of answers were dated as 2010-2011. It is quite surprisingly since this situatuion is so common.
Is there any changes from that times for Spring 4.+? Or maybe anyone can share personal experience how to beat this?
Thanks.
You can use validation group, and @Validated
annotation.
There's a detail explanation in http://www.javacodegeeks.com/2014/08/validation-groups-in-spring-mvc.html
The approach is based on hibernate validator's groups and it enables you to group the validation based on the marker interface and apply it on handler level, example as given in the link
@RequestMapping(value = "stepTwo", method = RequestMethod.POST)
public String stepTwo(@Validated(Account.ValidationStepTwo.class) Account account, Errors errors) {
if (errors.hasErrors()) {
return VIEW_STEP_TWO;
}
return "redirect:summary";
}