We're updating the issue view to help you get more done. 

Allow to pass a payload to the constraint validators

Description

Thanks to the work for HV-1497, done by @Marko Bekhta and @Guillaume Smet, we now have a HibernateConstraintValidator which provides us an initialize method that also takes a HibernateConstraintValidatorInitializationContext argument.

Which btw is great and I was waiting for something like this for years
Why?
Because, that addition allows us to easily pass a dynamic payload to each new instance of a HibernateConstraintValidator - which for us was a major pain so far to do. Right now we could only get a static payload from the annotation. But now we could pass a dynamic payload each time we call validator.validate(). E.g. in almost all applications we use HV we need to know the language or country of a user for the validation process - think of zip codes which differ for each country. With the current architecture of BV / HV this is basically impossible to achieve. That's why we used hacks like put the language / country (the "payload") into a ThreadLocal and retrieve the "payload" from that ThreadLocal inside the isValid method of a ConstraintValidator.

That's why I propose following addition the Hibernate Validator:

1 2 3 4 someValidator .unwrap(ValidatorImpl.class) .withDynamicConstraintValidatorInitializationPayload(payloadObject) .validate(objectToValidate)

Inside a HibernateConstraintValidator we can retrieve that payload like this:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 public class MyFutureValidator implements HibernateConstraintValidator<MyFuture, Instant> { private SomeType dynamicPayload; @Override public void initialize(ConstraintDescriptor<MyFuture> constraintDescriptor, HibernateConstraintValidatorInitializationContext initializationContext) { this.dynamicPayload = initializationContext.getDynamicPayload(SomeType.class); } @Override public boolean isValid(Instant instant, ConstraintValidatorContext constraintContext) { // Here I can use the dynamic payload now dynamicPayload.getSomeData(); //... } }

This withDynamicConstraintValidatorInitializationPayload / getDynamicPayload approach is the same we already use to pass a Dynamic payload as part of ConstraintViolation:
https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-dynamic-payload

Environment

None

Status

Assignee

Matthias Kurz

Reporter

Matthias Kurz

Labels

None

Worked in

None

Feedback Requested

None

Feedback Requested By

None

backPortable

None

Community Help Wanted

None

Suitable for new contributors

None

Requires Release Note

None

backportDecision

None

backportReEvaluate

None

Components

Fix versions

Priority

Major