Vaadin BeanValidationBinder with Custom Resource Bundle

blog-post-img

The BeanValidationBinder from Vaadin uses the default message bundle ValidationMessages from Bean Validation for translations. But often one has already a resource bundle with translations for the Vaadin application. So how can we override this resource bundle?

Creating a Custom MessageInterpolator

The way to that is by implementing your own MessageInterpolator. Luckily, a ResourceBundleMessageInterpolator from Hibernate Validator can be used to override the resource bundle name. Extend this class and in the constructor set the resource bundle name, in my case “messages”.

package com.example.application;

import org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator;
import org.hibernate.validator.resourceloading.PlatformResourceBundleLocator;

public class MyMessageInterpolator extends ResourceBundleMessageInterpolator {

    public MyMessageInterpolator() {
        super(new PlatformResourceBundleLocator("messages"));
    }
}

Configuring Bean Validation

Then you’ll have to configure Bean Validation. This is done with an XML file: validation.xml
This file must be placed in the classpath in the directory META-INF.

<?xml version="1.0" encoding="UTF-8"?>
<validation-config
        xmlns="http://xmlns.jcp.org/xml/ns/validation/configuration"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/validation/configuration/validation-configuration-2.0.xsd"
        version="2.0">

    <message-interpolator>com.example.application.MyMessageInterpolator</message-interpolator>

</validation-config>

That’s it. With this configuration Bean Validation will pick up the translations from the messages resource bundle.

Related Posts

Simon Martinelli
Follow Me