Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java bean validation: Optional fields annotation

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;
...

}

like image 591
salgaf Avatar asked Feb 16 '15 16:02

salgaf


2 Answers

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();
like image 154
Robert Schneider Avatar answered Nov 07 '22 15:11

Robert Schneider


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.

like image 44
Hardy Avatar answered Nov 07 '22 14:11

Hardy