How to localize Bean Validation messages
Asked Answered
G

3

11

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.

Gusella answered 5/11, 2014 at 16:7 Comment(0)
G
10

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

Gusella answered 5/11, 2014 at 16:40 Comment(1)
No need to extract anything. Just add the properties files you need or want to override. They need to be in the root of the classpath. User provided ValidationMessages properties file have precedence over the built-in ones.Eda
S
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

Shwa answered 5/11, 2014 at 16:17 Comment(0)
C
2

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;
Citified answered 5/10, 2018 at 7:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.