'How do I dynamically resolve message parameters with Hibernate Validator?
I'm using Hibernate Validator and would like to resolve the category's name in an error message. Consider this simple scenario:
public class Category {
private String name;
}
public class Product {
@HazardousCategoryConstraint(message = "{haz.cat.error}")
private Category category;
private String name;
}
public class InventoryReport {
@Valid
private List<Product> products;
}
ValidationMessages.properties
haz.cat.error={name} is a product in the hazardous category list.
Assume that I have a working implementation of HazardousCategoryConstraint. The validator checks each Category's name against a list of restricted names. When I call validate(InventoryReport) I get the number of errors I expect except they are the same string. I'd like to see the Category's name resolved into each message. Can someone point me to an example of how to resolve parameters dynamically, or show me how to?
Solution 1:[1]
public boolean isValid(FooEntity fooEntity, ConstraintValidatorContext context) {
//do some validation
boolean result = ...;
if (!result) {
HibernateConstraintValidatorContext hibernateContext =
context.unwrap(HibernateConstraintValidatorContext.class);
hibernateContext.disableDefaultConstraintViolation();
hibernateContext
.addMessageParameter("answer", "Like This!")
.addExpressionVariable("answer", "Like This!")
.buildConstraintViolationWithTemplate(hibernateContext.getDefaultConstraintMessageTemplate())
.addConstraintViolation();
result = false;
}
return result;
}
in the file:
.../resources/ValidationMessages.properties
com.example.validation.DaysLater.message = How do I dynamically resolve message parameters with Hibernate Validator? {answer}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | uniberg |
