I'm looking for a way to validate a java.lang.Double
field in the Spring command bean for its maximum and minimum values (a value must lie between a given range of values) like,
public final class WeightBean
{
@Max(groups={ValidationGroup.class}, value=Double.MAX_VALUE, message="some key or default message")
@Min(groups={ValidationGroup.class}, value=1D, message="some key or default message")
private Double txtWeight; //Getter and setter.
public interface ValidationGroup{}
}
But both @Max
and @Min
cannot take a java.lang.Double
value.
Note that double and float are not supported due to rounding errors (some providers might provide some approximative support)
So what is the way of validating such fields?
I'm working with Spring 3.2.0 and Hibernate Validator 4.3.1 CR1.
If you have switched to BigDecimal (or BigInteger), you could use @DecimalMin or @DecimalMax. But this is still no solution for float or double.
Sometimes it's convenient in pair with
@AssertTrue
/@AssertFalse
fromjavax.validation.constraints
I have avoided the
double
and thefloat
types and implemented a custom validator that could validate aBigDecimal
value based on the precision and the scale.The constraint descriptor.
The constraint validator.
This could be extended for other types as well, as and when required.
And finally in the bean, the property of the type
BigDecimal
could be annotated by the@BigDecimalRange
annotation as follows.You can use the annotation, but you might get false results depending. This is a general problem with doubles and imo in many cases _Double_s should be avoided. Maybe switching to a different type is the best solution? BigDecimal for example?
You can also use
@Digits
from the hibernate validator API as well