Search code examples
javaspring-mvchibernate-validator

How to escape arguments when using hibernate validator with a custom messagesource


I've something like:

<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basenames">
        <list>
            <value>...</value>
        </list>
    </property>
    <property name="defaultEncoding" value="UTF-8"/>
    <property name="fallbackToSystemLocale" value="false"/>
    <property name="useCodeAsDefaultMessage" value="true"/>
</bean>

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
    <property name="validationMessageSource" ref="messageSource"/>
</bean>

And some custom validator (has a values attribute) using this message:

validation.constraints.PossibleValues.message=The provided value "${validatedValue}" is invalid. Possible values: {values}

The issue is that the { and } are not there anymore in AbstractMessageInterpolator#interpolateMessage, so I don't get parameter interpolation.

I tried various escaping like '{'validatedValue'}', \\{ without success.

Does someone know how to escape the message arguments in such case?

(I saw this question, but it doesn't help)


Solution

  • I'm using almost the same configuration you have:

      <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="defaultEncoding" value="ISO-8859-1" />
        <property name="fallbackToSystemLocale" value="false" />
        <property name="useCodeAsDefaultMessage" value="false" />
        <property name="basenames" value="classpath:applicationMessages,classpath:ValidationMessages"/>
      </bean>
    

    And in my ValidationMessages.properties i overwrite some messages to Galician language using simple { and } for interpolated variables. For example:

    javax.validation.constraints.Min.message=debe ser maior o igual a {value}
    ...
    org.hibernate.validator.constraints.Length.message=debe ter unha lonxitude entre {min} e {max}
    

    The only strange behaviour is that if you want to put single quote you need to escape it with a single quote:

    org.hibernate.validator.constraints.ScriptAssert.message=o script ''{script}'' non devolve true
    

    Hope this helps.