Validator question (changing message in the validator class itself?)

I have quite a few validations where attributes need to be checked against each other (like dates in a scheduler not being backwards) and against other data (like a person not being scheduled at two different sites during the same time). Thanks to Validation in Java applications – Jmix I learned how to implement these types of validations as custom annotations/validator classes. It’s a wonderful mechanic and is so easy to read in the classes themselves, with the annotations.

However, in a couple cases I’d like to change the message shown based on the results of the logic in the validator class itself. I can’t figure out a way to do this, and can’t find a way looking through the Hibernate docs either.

So basically I’d like to have this…

.. class SomeCoolValidator implements ConstraintValidator<SomeCool, AnEntity> {
    ...
    public boolean isValid(AnEntity e, ConstraintValidatorContext context) {
        ... logic  ....
        if (logic failed) {
            // change message that will get displayed somehow...
       }
    }
}

Nevermind - more concentrated Googling reveals it’s as easy as:

            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(whatever you want here).addConstraintViolation();
1 Like