8

I would like to treat some fields as Optional, if the value is null or blank don't go with the checks of the other annotated constraints. There is some way to achieve it! Reading this tread Java bean validation: Enforce a @Pattern only when the property is not blank don't seems cover my needs. Below an example to explain what I mean:

public class Test  {
    
    @Max(value=100)         // <--mandatory
    private int parA;

    @Optional               // <-Custom annotation telling "do not check other if null or blank"
    @Range(min=10, max=200)
    private int parB;
    ...
}
Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
salgaf
  • 181
  • 2
  • 7

2 Answers2

11

Now you can!

https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#example-container-element-constraints-optional

public Optional<@Size(min=1, max=128) String> first_name = Optional.empty();
4

You cannot do what you want with Bean Validation. You cannot establish a "connection" between two constraints placed on a property. Also, if I understand correctly, your @Optional is not even a constraint annotation, but rather just a marker annotation. Note though, that all default constraints are implemented in a way that a constraint validates for null values. So in most cases you get what you want either way. In your example, you also have the problem that you are dealing with a primitive int. This will always have a value, so the range constraint would be evaluated either way.

Hardy
  • 18,659
  • 3
  • 49
  • 65
  • Thank you for the answer Hardy... Your understanding is correct... I will follow your suggestion – salgaf Feb 17 '15 at 09:17
  • +1 for "Note though, that all default constraints are implemented in a way that a constraint validates for null values. So in most cases you get what you want either way." That's why I came here :) – Dmitry Minkovsky Jul 09 '15 at 04:50
  • You totally can do it. Put an `@AssertTrue` validation constraint on a private `boolean`-returning property that checks the compound constraint. – Donal Fellows Sep 12 '22 at 12:57