简体   繁体   English

Java中的条件验证

[英]Conditional Validation in Java

I am trying to do bean validation in a Object graph. 我正在尝试在对象图中进行bean验证。 Lets say I have two classes called Foo and Bar. 可以说我有两个叫做Foo和Bar的类。 They have @OneToOne relationship. 他们有@OneToOne关系。

Foo.class 让Foo.class

class Foo
{
    String a;
    String b;
    boolean c;

    @Valid
    Bar bar;
}

Bar.class Bar.class

class Bar
{
    String i;
    String j;
    String k;
    String l;
}

I want to validate Both Foo and Bar but I want to do conditional validation on Bar depending on the value entered in Foo.class. 我想同时验证Foo和Bar,但是我想根据Foo.class中输入的值对Bar进行条件验证。 Depending on the value of c in Foo.class, I want to validate the fields in Bar.class. 根据Foo.class中c的值,我想验证Bar.class中的字段。 If c is true, then I want to validate i and j. 如果c为真,那么我想验证i和j。 If c is false then I want to validate k and l. 如果c为假,那么我想验证k和l。

Is there anyway I can do it? 反正我能做到吗?

I don't think there's anything out there that does what you want out of the box. 我认为没有什么可以满足您的要求。 This said, there is JSR 303 which allows you to annotate your classes with custom validators. 就是说 ,这里有JSR 303 ,它允许您使用自定义验证器注释类。 I suppose you could write a validator that can use some custom annotation you'd make and put on the boolean that dictates whether or not to run the Bar validator. 我想您可以编写一个验证程序,该验证程序可以使用您将要进行的一些自定义注释,并放在指示是否运行Bar验证程序的布尔值上。

With plain Bean Validation it is not possible to do what you are asking. 使用普通的Bean验证,您将无法完成所要求的操作。 Hibernate Validator has a provider specific feature which is called @GroupSequenceProvider . Hibernate Validator具有特定于提供程序的功能,称为@GroupSequenceProvider With this feature you can change the group sequence which gets executed when validating an object. 使用此功能,可以更改验证对象时执行的组顺序。 See also http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#d0e3062 另请参见http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#d0e3062

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM