I implemented my own annotation and ConstraintValidator (JSR-303). During the validation process I want to create different error codes:
public class SomeValidator implements ConstraintValidator<ConstraintAnnotation,SomeObject> {
@Override
public void initialize (ConstraintAnnotation constraintAnnotation) {
}
@Override
public boolean isValid (SomeObject some, ConstraintValidatorContext context) {
int parameter = some.getParameter();
if (parameter==1){
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate("SomeObject.code.first").addConstraintViolation();
return false;
}
if (parameter==2){
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate("SomeObject.code.second").addConstraintViolation();
return false;
}
return true;
}
}
But context.buildConstraintViolationWithTemplate() adds an error message not a code. So spring ties to expand code like this:
ConstraintAnnotation.someObject
not
SomeObject.code.second
How add custome code instead of message?
The problem was solved very simple:
1) Surround error code with {} like this:
context.buildConstraintViolationWithTemplate("{SomeObject.code.first}").addConstraintViolation();
2) Add properties files to resources folder (it is resources folder in maven project):
ValidationMessages_en_US.properties
ValidationMessages_en_US.properties file content
SomeObject.code.first=Illegal link value
After that validation produces the code not message and spring resolves error codes to actual messages.
NOTE:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With