【问题标题】:Optional multiple same constraints on field using Bean Validation使用 Bean Validation 对字段的可选多个相同约束
【发布时间】:2012-06-05 11:26:34
【问题描述】:

我正在尝试使用 Hibernate 验证器在插入数据库之前验证 POJO。

bean 中有一个长度可以是 8 或 10 的字段。

我尝试使用内置约束 List 将它们放在一起,期望其中一个条件通过而不是验证通过。

@Length.List({@Length(min=8, max=8,message="Code is either 8 or 10 characters in length"),@Length(min=10, max=10,message="Code is either 8 or 10 characters in length")})
public String getCode() {
    return this.code;
}

但是,结果显示列表中的所有条件都必须通过才能使其有效。所以我想知道是否有办法改为进行 OR 检查。

【问题讨论】:

    标签: java validation jpa-2.0 hibernate-validator


    【解决方案1】:

    我觉得这个注​​解的工作方式是这样的:

    @Length(min = 8, max = 10)  
    public String getCode() {
       return code;
    }
    

    换句话说,9 也将被视为有效,这不是您想要的。我不确定是否有办法在 Hibernate 注释中对它们进行两次验证和 OR 操作。

    看来您可以为此使用@Pattern 验证:

    @Pattern(regexp="(.{8}|.{10})", message="Should either be 8 or 10 characters")
    public String getCode() {
       return code;
    }
    

    【讨论】:

    • 我试过了,因为我在网上阅读了一篇文章来引导我这样做。无论如何,你的方法是有效的。谢谢!
    猜你喜欢
    • 2015-06-12
    • 2011-03-30
    • 2010-12-14
    • 1970-01-01
    • 2012-04-05
    • 1970-01-01
    • 2016-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多