The Java EE 6 Tutorial

Specifying Error Messages for Constraints in address-book

Some of the constraints in the Contact entity specify an optional message:

@Pattern(regexp="^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$",
             message="{invalid.phonenumber}")
    protected String homePhone;

The optional message element in the @Pattern constraint overrides the default validation message. The message can be specified directly:

@Pattern(regexp="^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$",
             message="Invalid phone number!")
    protected String homePhone;

The constraints in Contact, however, are strings in the resource bundle tut-install/examples/persistence/address-book/src/java/ValidationMessages.properties. This allows the validation messages to be located in one single properties file and the messages to be easily localized. Overridden Bean Validation messages must be placed in a resource bundle properties file named ValidationMessages.properties in the default package, with localized resource bundles taking the form ValidationMessages_locale-prefix.properties. For example, ValidationMessages_es.properties is the resource bundle used in Spanish speaking locales.