Search code examples
javavalidationbean-validationhibernate-validator

JSR303 Validation: Pass in an Object/Context Information at runtime?


I have an List of String-IDs in a bean that I like to validate against a "Reference List" of String ids:

@MyIdListValidator  
private List<String> idsFromHtmlForm;  //These need to be validate against an ID list from DB

So I have to somehow inject the "Reference List" with all valid values to check against at rumtime. (These reference ids read/generated from the database at runtime). This is a webapplication (Struts) and I am really wondering why this seems to be not possible, but is a use-case that is prevalent in millions of webapplications. How do you solve this?

Is there some way to either inject any arbitrary information (context objects) to the validator.validate(form); method?

And is there an easy way to get access to the whole(!!) object being validated in this method:

public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) of ConstraintValidator<Date,String>,

Note: My question is not related to class level validations, but to property level validations if there is a trick to get access to the whole object (the property belongs to), not only the value of a property itself. (If I would have access to the whole instance/class being validated I could set the data there as a secondary property, it is messy but would be a solution).

Thanks very much


Solution

  • With Bean Validation that is not possible. Only class level constraints have access to the validation root. A property level constraint has only access to the validated value. This might change in Bean Validation 1.1.

    You could write your custom ConstraintValiatorFactory which allows injection.