Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How add error code to ConstraintValidator in Spring?

Tags:

java

spring

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?

like image 447
Cherry Avatar asked Apr 10 '13 10:04

Cherry


1 Answers

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
like image 84
Cherry Avatar answered Oct 02 '22 20:10

Cherry