0

I have List of Objects that I need to run some validation on

    @KeyValid
    @Valid
    protected List<KeyValue> keyValues;

and I have a the following annotation created for it:

@Target({ElementType.TYPE, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = KeyValidator.class)
public @interface KeyValid{

    String message() default "invalid_parameter_default_message";

    String[] checks() default {};

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

And this is my validator:

public class KeyValidator implements ConstraintValidator<KeyValid, KeyValue> {

    @Override
    public void initialize(KeyValid keyValid) {

    }

    @Override
    public boolean isValid(KeyValue keyValue, ConstraintValidatorContext constraintValidatorContext) {    

        return true;
    }
}

I had read somewhere that collections can be validated in bulk if the list or map or set is annotated by custom constraint then all of the elements of the collection call the validator but the above code throws the following error

javax.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'com.util.Validators.KeyValid' validating type 'java.util.List<com.model.KeyValue>'. Check configuration for 'keyValue'
Nick Div
  • 5,338
  • 12
  • 65
  • 127

1 Answers1

0

Your constraint would get the actual List passed not its elements. If you are using Java 8 and the latest version of Hibernate Validator, you can use type argument constraints. You just have to make sure to also add ElementType.TYPE_USE to @Target in your constraint. Type argument constraints are not yet official part of Bean Validation, but will be in the next version of it (BV 2.0).

You would have something like this:

protected List<@KeyValid KeyValue> keyValues;

Alternatively, could you not put the @KeyValid constraint as class level constraint on KeyValue?

Hardy
  • 18,659
  • 3
  • 49
  • 65
  • Unfortunately I am stuck with Java 7 for now, but I did read about the annotations along the parameter declaration. Looks good. But is there a way I can do something with Java 7 and also I cannot add the annotation to the class directly because it is a generated source. – Nick Div Jul 06 '16 at 14:33
  • 1
    You could use the Hibernate Validator API for programmatic constraint declaration to add the constraint to the class definition of `KeyValue`. That way you don't need to touch its source code and can simply validate the list via `@Valid`. – Gunnar Jul 08 '16 at 08:19