问题
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.
回答1:
Managed to overcome this without messing with the hibernate jar.
If we want to override default ValidationMessages.properties
:
- 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. - Put all all in our project's
src/main/resources
folder. So the folder contains all the *.properties files. - *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 atsrc/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
回答2:
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
回答3:
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;
来源:https://stackoverflow.com/questions/26761752/how-to-localize-bean-validation-messages