Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
804 views
in Technique[技术] by (71.8m points)

java - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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";
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...