Search code examples
javaspringspring-webflow-2

Using ValidationMessages bundle with Spring Webflow Validation?


How do I wire up a Spring ValidationMessages bundle in a custom Webflow Validator class? I have a validator implemented and working:

public void validateBusinessReferences(BusinessReferencesViewDao businessReferences, Errors errors) {
    if (somecondition())) {
        errors.rejectValue("name", "validation.message123", "This field is bad.");
    }
}

But instead of the message from the ValidationMessages.properties file, I get the fallback default of This field is bad.

All my other messages and validations work fine - it's just this custom validator/custom message scenario that's failing. I suspect a Spring configuration problem of some kind but I can't isolate it.


Solution

  • Problem solved - I was missing a step. In order to use a properties bundle you need to use a MessageResolver and call it like so:

    MessageResolver messageResolver = new MessageBuilder().error().source(source).code("validation.message.property.here").defaultText(errorMessage).build();
    messageResolver.resolveMessage(messageSource, Locale.ENGLISH);
    return messageResolver;
    

    Where your messageSource is your Spring bean with your message properties bundles, defined in your application context:

    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basenames">
            <list>
                <value>messages</value>
                <value>ValidationMessages</value>
            </list>
        </property>
    </bean>
    

    Documentation on MessageResolver is here.