Java Bean Conditional Validation

Viewed 4579

I have a class with two attributes. I want to use Java Bean Validation but ran with one problem on how to approach?

class ProductRequest {

   private String quantityType;
   private double quantityValue;

   //getters and setters
}

I want to use Java Bean Validation based on below condition. If "quantityType" is equals to "foo", limit "quantityValue" to maximum size of 5 else "quantityType" is equals to "bar", limit "quantityValue" to maximum size of 3.

What will be the best way to approach in this scenario?

1 Answers
import javax.validation.constraints.AssertTrue;


@AssertTrue
public boolean isBothFieldsValid() {
    if (quantityType.equals("foo")) {
        return quantityValue < 5;
    } else if (quantityType.equals("bar")) {
        return quantityValue < 3;
    }
    return false;
}

EDIT:

Addressing question from comment. You can try using two methods at once:

@AssertTrue(message = "quantity should be below 5 for foo")
public boolean isQuantityValidForFoo() {
    if (quantityType.equals("foo")) {
        return quantityValue < 5;
    }
    return true;
}

@AssertTrue(message = "quantity should be below 3 for bar")
public boolean isQuantityValidForBar() {
    if (quantityType.equals("bar")) {
        return quantityValue < 3;
    }
    return true;
}
Related