0

I was wandering if anyone could help me figure out how to validate a floating point. I have an annotation which validates only whole numbers and I need the input field to be able to except a decimal value, but not a 0.

Things I have tried:

@Range(min=(long)0.1)

This doesn't work and allows 0 to be passed as a valid input. public float hoursUsed;

@ DecimalMin(0.1)
public BigDecimal hoursUsed;

I tried changing the type of the variable to a BigDecimal which I could then Validate using @DecimalMin(min=0.1). However I then get an error when trying to manipulate this data.
"The operator * is undefined for the argument type(s) BigDecimal, float"

Trying to cast the float value to a BigDecimal results in the error
"The operator * is undefined for the argument type(s) java.math.BigDecimal, BigDecimal"

I have also tried to create a customConstraintValidator annotation which would then return a validation error if the input returns a 0. That way I could Just simply use @Range(min=0) and a custom annotation (for example) @NotZero to ensure the input is indeed grater than a 0.

This results in an error in the ConstraintValidator as I can not pass in a floating point value through the generic method. The error is:
"Syntax error, insert "Dimensions" to complete ReferenceType".

Basically my question is how can I validate a floating point?

Chris
  • 103
  • 3
  • 15
  • Probably not an efficient way but you can do this in a try catch block making use of `NumberFormatException` – Ulug Toprak Apr 13 '17 at 13:52
  • I think you'll beter to check this answer http://stackoverflow.com/questions/15488990/validating-double-and-float-values-using-hibernate-validator-bean-validation – Serg Shapoval Apr 13 '17 at 13:52
  • Oh the joys of enterprise. Back in the day, we would just call Float.parseFloat(), and catch any exceptions. – Steve Smith Apr 13 '17 at 13:54
  • The question you have posted suggests switching the type to a BigDecimal, which I can not seem to do as I can not then manipulate the input as `" * is undefined for the argument type(s) java.math.BigDecimal "` – Chris Apr 13 '17 at 13:57
  • @Steve Smith i must be still living in the good old days :) that is exactly what i suggested :) – Ulug Toprak Apr 13 '17 at 14:00
  • Could either of you give me a little bit more information on how I would implement this? I need the input field to be validated and display an error to the user if the input does not pass said validation.(like `@Range` does, yet with a float). – Chris Apr 13 '17 at 16:01

0 Answers0