Java Reference
In-Depth Information
Class<?>[] groups() default {};
}
Implementing a validator
Instead of a processor that is required for simple annotations, constraints need to
implement the
javax.validation.ConstraintValidator <A extends An-
notation, T extends Object>
interface, which provides two methods that are
as follows:
•
void initialize(A constraintAnnotation)
: This method is always
called before processing a constraint. It allows you to initialize the paramet-
ers that will be useful during the execution of the
isValid()
method.
•
boolean isValid(T value, ConstraintValidatorContext con-
text)
: This method contains the validation logic.
The following code shows the validator of our constraint:
public class CaseValidator implements
ConstraintValidator<Case, String>{
private CaseType type;
public void initialize(Case annotation) {
type = annotation.type();
}
public boolean isValid(String
value,ConstraintValidatorContext context) {
if(value == null)
return true;
if (type == CaseType.UPPER) {
return value.equals(value.toUpperCase());
} else {
return value.equals(value.toLowerCase());
}