Steve Chambers Steve Chambers - 1 month ago 7
Java Question

How to implement multiple JSR-303 validation messages for the same @Constraint?

I'm using JSR-303 validation (hibernate-validator) for an entity with a few different rules to be applied. Would rather not stack up multiple

annotations for these and instead use a single one, e.g.

Problem is there really needs to be a different message for each type of validation failure but the message seems inextricably associated with the annotation:

public @interface MyEntityConstraint {
String message() default "A single, unchangeable message per constraint???";
// ...

Is there any way round this or am I doomed to have:

// ...
public class MyEntity {
// ...


Have a look at ConstraintValidatorContext passed to the isValid method of your constraint validator. It allows you to customize the error messages which includes using different message templates depending on your validation state.