Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

exclude some fields from @Valid validation

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.

like image 521
fasth Avatar asked Apr 22 '15 12:04

fasth


Video Answer


1 Answers

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";
}
like image 114
Master Slave Avatar answered Oct 15 '22 22:10

Master Slave