March 7, 2015

Dynamic localization of JSR 303 validation messages with wildcards

Lets say you have a class like this

And you want to localize the messages in a file, you might do something like this:

Now you have hardcoded the values in multiple places, imagine if you have multiple properties files for different languages, you would define the values everywhere!

Instead you can do this:

And this:

Now, why are we using {2} and {1}?

The attributes are ordered alphabetically! From the board:

For the first option, Spring-managed field error arguments include the actual constraint annotation attributes in alphabetical order now. So for @Size(min=1,max=5), it’ll include the field name as {0} , the max value as {1} , and the min value as {2}

Has caught me many times.