10

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?

1 Answer 1

10

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:

  1. Actually you can put ValidationMessages_en_US.properties (and other i18n properties files) every where in spring project. If you put it in other location you need to configure LocalValidatorFactoryBean, in theory, in practice I could not do it, codes were not resolved in my case and I put property file in resources folder.
  2. You can create custom error message like: "Error message. {error.code}" and "error.code" will be replaced with property in the file. See JSR-303 specification
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.