Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to localize Bean Validation messages

I have a class and using annotation to validate the class properties.

My web page (jsf2.2/primefaces/maven) is multilanguage (DE-utch, FR-rench, IT-alian).

My problem is that the hibernate-validator has support for some languages(de, en, es, fr, hu, tr, pt_BR, mn_MN, zn_CN) but not Italian! (listed in the jar, org->hibernate->validator) So when i use the Italian version of my web page the validation messages are shown in english(default choice of hibernate).

How i can override this, and provide custom italian validation messages?

I don't want to mess with the hibernate jar, because the project is maven and the jar is automatically fetched.

like image 322
oikonomopo Avatar asked Nov 05 '14 16:11

oikonomopo


3 Answers

Managed to overcome this without messing with the hibernate jar.


If we want to override default ValidationMessages.properties:

  1. We can pick the appropriate files (hint:copy them from the hibernate jar: ValidationMessages.properties, ValidationMessages_de.properties, ValidationMessages_fr.properties) and edit them accordingly.
  2. Put all all in our project's src/main/resources folder. So the folder contains all the *.properties files.
  3. *To provide validations for more languages (except of hibernate's default langs), f.e. the italian language, we create a ValidationMessages_it.properties and put it at src/main/resources folder. (src/main/resources/ValidationMessages_it.properties).

After all, when locale is set to italian language, hibernate will look first at latter folder, in case of any overridden/other validation messages (like ValidationMessages_*.properties), and use them instead of default ones!

Caution This solution is for MAVEN project, otherwise you should put *properties.files at /src/main/java folder, as mentioned in another similar question comment

like image 156
oikonomopo Avatar answered Nov 19 '22 20:11

oikonomopo


You can provide your own language file by putting the

 ValidationMessages_it_IT.properties

on your classpath.

This question is a duplicate of Localization with bean validation in JSF

like image 28
Simon Zambrovski Avatar answered Nov 19 '22 22:11

Simon Zambrovski


Put properties files under src/main/resources folder, they should be named ValidationMessages_{locale code}.properties, the default one should be ValidationMessages.properties , the contents are looking like:

invalid.phone.number = Invalid phone number

Then in your bean:

@Pattern(regexp = "^[0-9]+[0-9\\-]{3,}[0-9]+$", message = "{invalid.phone.number}")
    private String number;
like image 1
marknote Avatar answered Nov 19 '22 21:11

marknote