i18n and type conversion validation messages with Spring

Posted on by George Georgovasilis

Given a form backing object (aka command object) which contains a nummeric field, i.e.

class OrderQuery{
int sequence;
// getters & setters
}

And the corresponding JSP form:

...

<form:form commandName="searchOrderQuery" method="POST" ... >
<form:input path="sequence />
<form:errors path="sequence"/>
...
</form:form>

One gets a non-localized, quite technical validation error when entering a text instead of a number:

<div class="portlet-msg-error">
<span id="documentId.errors" class="error">Failed to convert property value of type java.lang.String to required type int for property documentId; nested exception is java.lang.NumberFormatException: For input string: "asdad"</span>
</div>

Spring allows the localization (read: substitution) of that message with a little documented feature [1] which resolve error messages with the typeMismatch prefix, thus my messages property file now looks like this:

typeMismatch.sequence = Must be a number

Resources

[1] Spring DataBinder

http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/validation/DefaultMessageCodesResolver.html

This entry was posted in spring and tagged i18n, validation by George Georgovasilis