1

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.

Urr4
  • 611
  • 9
  • 26
  • Hi, check if this is answer to your problem https://stackoverflow.com/questions/23702975/building-dynamic-constraintviolation-error-messages – mommcilo Sep 24 '20 at 11:23

1 Answers1

2

It's quite simple: Just call a context inside isValid area:

context.buildConstraintViolationWithTemplate("message here");

Enjoy!

Alex
  • 153
  • 11
  • 1
    That was it, thanks. To be complete, I should have disabled the default message with context.disableDefaultConstraintViolation() and added the new one with context.buildConstraintViolationWithTemplate("my custom message").addConstraintViolation(). Thank you – Urr4 Sep 24 '20 at 13:35