no error message when custom constraint gets violated

Go To


I have the following code for my custom Constraint:

@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;

public void initialize(CheckMinMax annotation) {
    max = annotation.max();
    min = annotation.min();


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:


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" ?


2012-04-03 20:57
by Moonlit


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) 


2012-04-05 22:51
by Moonlit


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);
2012-04-03 21:35
by Piotr Kochański
hi and thank you for your answer. the set requires a type parameter. Set> cvs; But the constructor of ConstraintViolationException don't accept it. (The constructor ConstraintViolationException(Set>) is undefined) : - Moonlit 2012-04-03 22:46