Validating double and float values using Hibernate Validator - bean validation

Tiny picture Tiny · Mar 19, 2013 · Viewed 33.1k times · Source

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.

Answer

Hardy picture Hardy · Mar 19, 2013

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?