3

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?

Sushan Baskota
  • 315
  • 3
  • 10

1 Answers1

7
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;
}
Krystian G
  • 2,842
  • 3
  • 11
  • 25
  • Just to be sure Krystian, I need to add this method on the same model class right? And how will it be triggered for input validation ? – Sushan Baskota Aug 29 '18 at 12:55
  • Yes, add it to ProductRequest class. I assumed you're already using some validation annotation like '@NotNull' and this one works exactly the same. It works as a getter to new field `@AssertTrue private boolean bothFieldsValid;`. https://stackoverflow.com/questions/6283726/jsf-jsr-303-bean-validation-why-on-getter-and-not-setter – Krystian G Aug 29 '18 at 15:21
  • Thanks, it worked! Do you have any idea of setting different message for false condition of @AssertTrue based on these condition ? i.e if equals to "foo" and quantity >= 5 , @AssertTrue(message = "quantity should be below 5 for foo") and if equals to "bar" and quantity >= 3 then @AssertTrue(message = "quantity should be below 3 for bar") ? – Sushan Baskota Aug 29 '18 at 15:40
  • Perfect! This is way I was looking for. Thanks, Krystian. – Sushan Baskota Aug 30 '18 at 16:17