I have the following code for my custom Constraint:
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.FIELD, ElementType.METHOD })
@Constraint(validatedBy = MinMaxValidator.class)
public @interface CheckMinMax{
String message() default "MinMax constraint has been violated";
Class<? extends Payload>[] payload() default {};
Class<?>[] groups() default {};
int min() default 1;
int max() default 10;
}
And the Validator class:
public class MinMaxValidator implements ConstraintValidator {
int max;
int min;
@Override
public void initialize(CheckMinMax annotation) {
max = annotation.max();
min = annotation.min();
}
@Override
public boolean isValid(Integer value, ConstraintValidatorContext arg1) {
if (value < min || value > max)
return false;
return true;
}
}
now when i annotate my entitybean whith my annotation and try to pass in an object which violates my constraint with following code:
validator.validate(obj);
it works, but there is no error message... Is here something missing? How can i manage it to output the default error message "MinMax constraint has been violated" ?
thx
I figured it out how you can print out the error message defined in the Annotation:
Set<ConstraintViolation<TypeOfObj> cvs = validator.validate(obj);
for(ConstraintViolation<TypeOfObj> violation : cvs)
{
logger.info(violation.getMessage());
}
cheers
Validator.validate()
method is not throwing the ConstraintValidationException. It returns Set<ConstraintViolation>
, you are responsible for throwing the exception if there are any constraint violations.
The typical usage pattern would be:
Set<ConstraintViolation> cvs = validator.validate(obj);
if(cvs.size() > 0){
throw new ConstraintViolationException(cvs);
}