Steve Chambers Steve Chambers - 1 year ago 74
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 {
// ...

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download