从@Valid 验证中排除某些字段 [英] exclude some fields from @Valid validation

查看:48
本文介绍了从@Valid 验证中排除某些字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Spring 的 @Valid 注释来验证 bean 的字段,这些字段用 javax.constraints 注释进行注释.

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

我进行了调查,没有发现任何有用的方法,大多数答案的日期为 2010-2011 年.这种情况太普遍了,真是令人惊讶.

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.

Spring 4.+ 从那时起有什么变化吗?或者,也许任何人都可以分享个人经验如何打败这个?

Is there any changes from that times for Spring 4.+? Or maybe anyone can share personal experience how to beat this?

谢谢.

推荐答案

您可以使用验证组,以及 @Validated 注释.

You can use validation group, and @Validated annotation.

http://www 中有详细解释.javacodegeeks.com/2014/08/validation-groups-in-spring-mvc.html

该方法基于 hibernate 验证器组,它使您能够根据标记界面对验证进行分组并将其应用于处理程序级别,例如链接中给出的示例

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

这篇关于从@Valid 验证中排除某些字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆