I'm having a class X
that has three fields: state
(an enum of A
and B
), a
and b
.
When state
is A
, a
must not be null
, when state
is B
, b
must not be null
.
@ValidateCondition(message = "Validation failed")
public class X {
private State state;
private String a;
private String b;
}
Using hibernate-validator, I've build the following Validator:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = MyValidator.class)
@Documented
public @interface ValidateCondition {
String message() default "ValidateCondition failed";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class MyValidator implements ConstraintValidator<ValidateCondition, X> {
@Override
public boolean isValid(X x, ConstraintValidatorContext context) {
if(x.getState()==State.A){
return x.getA() != null;
}
if(x.getState()==State.B){
return x.getB() != null;
}
}
}
So whenever validation fails, I currently get the message Validation failed
, but what I want would be a message, telling me why it failed, like Since state was B, b must not be blank
.
I'm assuming I can somehow use the ConstraintValidatorContext
for that, but I don't know if or how.