Muhammad Hewedy
Muhammad Hewedy

Reputation: 30056

i18n for bean validation messages

I've the following code to do bean validation:

ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<MyObject>> validations = validator.validate(myObject);
if (!CollectionUtils.isEmpty(violations)) {
    for (ConstraintViolation<?> validateError : violations) {

    }
}

Is there any way to get the message from standard bean-validation resource files?

I am using the following (non-standard way):

Messages.get(validateError.getMessageTemplate().substring(1, 
     validateError.getMessageTemplate().length() - 1),locale);

Upvotes: 3

Views: 1450

Answers (1)

Hardy
Hardy

Reputation: 19119

Assuming you want to change the interpolation Locale depending on some external criteria (for example the users Locale), you can specify a custom MessageInterpolator when bootstrapping Bean Validation. You can either do that via XML and validation.xml or programmatically like so:

ValidatorFactory validatorFactory = Validation.byDefaultProvider()
        .configure()
        .messageInterpolator( new MyMessageInterpolator() )
        .buildValidatorFactory();
Validator validator = validatorFactory.getValidator();

In MyMessageInterpolator you can then for example retrieve the (users) Locale via ThreadLocal. You can then pass the actual validation to the default message interpolator (accessible via Configuration#getDefaultMessageInterpolator() during bootstrapping) using the interpolate method of MessageInterpolator which takes an explicit Locale instance:

public String interpolate(String messageTemplate, Context context, Locale locale) 

Upvotes: 3

Related Questions