Let's say I am using Hibernate Validator and I write the following code:
@Email
@Range(min=3,max=7)
public String getSomething() {
// ...
}
The @Email
annotation works on CharSequence
implementations (Strings, etc.) only. The @Range
annotation works on numeric types only.
When I execute this code, nothing special happens. getSomething()
does the same exact thing it did before I added these annotations.
How do I use Hibernate Validator to detect that I can't use these two annotations together? Thanks in advance!
According to the JavaDoc the @Range
constraint also works for string representations of numbers. So everything is alright here from Hibernate Validator's perspective.
Note that invoking the getSomething()
method doesn't automatically trigger an evaluation of the constraints. To validate the constraints, use the javax.validation.Validator
API. In case of misplaced constraints (e.g. @Email
put to a number), Hibernate Validator will throw an exception during validation (e.g. upon invocation of Validator#validate()
.
In order to detect misplaced at compile time instead of runtime you can use the annotation processor provided by Hibernate Validator. This processor can be plugged into the javac compiler or your IDE and will raise a compile error if it detects illegal constraints.