Search code examples
bean-validationhibernate-validator

Hibernate validation: validate PI


I'm in need to apply a validation on a double value which needs to match with PI. I'm thinking to use a @Pattern(regex="3.14159265359"). Is it the best way I can apply such a constraint using Hibernate Validation Constraints? Thanks


Solution

  • @Pattern is only defined for string type (CharSequence really). If your data type is a double you cannot use it, unless you write a custom ConstraintValidator. You could use DecimalMin in combination with DecimalMax potentially allowing for some imprecision. Alternatively, you could write your own constraint @Pi which for example allows to specify a delta. @Pi is probably the best solution, provided you really need this validation.