Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace default message for Constraint Validator

Tags:

java

spring

I'm trying to change the default message of a Constraint Validator in Spring.

I tried adding the new message depending on the validation error like this:

context.buildConstraintViolationWithTemplate("My custom message").addConstraintViolation();

for every case.

@Override
public boolean isValid(MyData data, ConstraintValidatorContext ctx) {
    boolean valid = false;
    if (!StringUtils.isEmpty(data.getDocumentType())) {
        if (data.getDocumentType().equalsIgnoreCase("N")) {
            valid = isValidTypeN(data.getDocument());
            if(!valid) context.buildConstraintViolationWithTemplate("My custom message for type N").addConstraintViolation();
        } else if(data.getDocumentType.equalsIgnoreCase("R")){
            valid = isValidTypeR(data.getDocument());
            if(!valid) context.buildConstraintViolationWithTemplate("My custom message for type R").addConstraintViolation();
        } else if(data.getDocumentType.equalsIgnoreCase("P")) {
            valid = isValidTypeP(data.getDocument());
            if(!valid) context.buildConstraintViolationWithTemplate("My custom message for type P").addConstraintViolation();
        }
    }       
    return valid;
}

But this is adding a new message not replacing the default message from the Constraint so when I show the errors in the form page, it shows both of them the default and the one I added instead of only the one I added dynamically.

like image 832
Kronen Avatar asked May 24 '26 23:05

Kronen


1 Answers

This code should do the job:

context.disableDefaultConstraintViolation()
like image 65
Maksym Avatar answered May 27 '26 12:05

Maksym



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!