0

A bean class with multiple fields. When checking, if A is empty, check B, otherwise do not check B. And I need to set the message according to different checks.

I have many such validations, can hibernate validator be easily implemented?

Now I write like this

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 ");
            }
        }
        
        //....
    }
}
Ulimp
  • 1
  • 1
  • 1
    Does this answer your question? [How can I validate two or more fields in combination?](https://stackoverflow.com/questions/2781771/how-can-i-validate-two-or-more-fields-in-combination) – XtremeBaumer Jul 19 '22 at 06:53
  • `if (order.getA().isEmpty() ^ order.getB().isEmpty() { // ... } ` – Arsegg Jul 19 '22 at 06:54
  • @XtremeBaumer Can I use ConstraintValidator to set the message according to different validations? – Ulimp Jul 19 '22 at 07:03
  • @Ulimp you can pass the message as a property of the annotation. – Augusto Jul 19 '22 at 08:23

1 Answers1

0

well it is because when A is empty B is not even checked because the check goes around. To improve your if I would use this:

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 ");
        }
        
        //....
    }
}

Or you could use annotations to check whether the field is empty or null.

Sanady_
  • 68
  • 10