Java bean validation: Optional fields annotation
Asked Answered
B

2

10

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;
    ...
}
Burge answered 16/2, 2015 at 16:32 Comment(0)
P
13

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();
Purdah answered 26/1, 2019 at 1:11 Comment(0)
D
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.

Dictatorial answered 17/2, 2015 at 9:3 Comment(3)
Thank you for the answer Hardy... Your understanding is correct... I will follow your suggestionBurge
+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 :)Rutilant
You totally can do it. Put an @AssertTrue validation constraint on a private boolean-returning property that checks the compound constraint.Glutton

© 2022 - 2024 — McMap. All rights reserved.