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;
...
}
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With