【问题标题】:Hibernate validator - field A or B can be empty, but both A and B cannot be emptyHibernate 验证器 - 字段 A 或 B 可以为空,但 A 和 B 都不能为空
【发布时间】:2022-07-19 14:54:44
【问题描述】:

具有多个字段的 bean 类。检查时,如果A为空,则检查B,否则不检查B。而且我需要根据不同的检查设置消息。

我有很多这样的验证,hibernate验证器可以轻松实现吗?

现在我是这样写的

public class Order
{
    private String a;
    private String b;
    
    //.... other fields
}

public class Validation
{
    public void valid(Order order) throws Exception
    {
        if (order.getA().isEmpty())
        {
            if (order.getB().isEmpty())
            {
                throw new Exception("xxx message ");
            }
        }
        
        //....
    }
}

【问题讨论】:

标签: java bean-validation hibernate-validator


【解决方案1】:

这是因为当 A 为空时,B 甚至没有被检查,因为检查会到处进行。如果我会使用这个来改进你:

public class Order
{
    private String a;
    private String b;
    
    //.... other fields
}

public class Validation
{
    public void valid(Order order) throws Exception
    {
        if (order.getA().isEmpty() && order.getB().isEmpty())
        {
            throw new Exception("xxx message ");
        }
        
        //....
    }
}

或者您可以使用注释来检查该字段是否为空或为空。

【讨论】:

    猜你喜欢
    • 2011-08-10
    • 2014-03-29
    • 1970-01-01
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    • 1970-01-01
    相关资源
    最近更新 更多