Search code examples
javaspringhibernatehibernate-validator

Spring hibernate type validation with multiple error messages


I'm wondering if such a thing is possible. I have a general DTO class called "Device". Device holds ID and IP. I've set a inner regexp validation to verify if the IP is entered correctly.

But now I want to have another validation of type "verify if this IP is not used by another device"(for both update and create cases).

For this I have written a custom Type orientated ConstraintValidator, where I accomplish the task of checking if the is no other device with the given IP.

But from this point I wanted to go further, and to have several checks and several response error messages from one ConstraintValidator, doing random checks on the Device object.

On this point I couldn't find if I could redefine validator's error message. Is this possible?


Solution

  • You can do this using the following function I use for my own API :

    public static void setNewErrorMessage(String newErrorMessage, ConstraintValidatorContext context) {
    
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate(newErrorMessage)
                .addConstraintViolation();
    }
    

    The context object here is passed in the isValid function of any ConstraintValidator implementing class.

    This way you'll be able to do something like :

    if(hasError1()) {
         setNewErrorMessage(ERROR1_MESSAGE, context);
         return false;
    }
    
    if(hasError2()) {
         setNewErrorMessage(ERROR2_MESSAGE, context);
         return false;
    }