Reputation: 466
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.
Upvotes: 9
Views: 5293
Reputation: 86
This code should do the job:
context.disableDefaultConstraintViolation()
Upvotes: 7