Customizing error messages for validators

The error messages that are shown for each type of validation error are controlled by the Message.properties file, which is located in the javax.faces package of jsf-api.jar. You can customize/replace these error messages with your own or you can add new messages. Also, you can provide messages in different languages, not just in English. In this recipe, we will customize error messages using three scenarios, as follows:

  • Customizing the default messages from Message.properties
  • Creating our own error messages
  • Generating error messages from custom converters

Getting ready

We developed this recipe with NetBeans 6.8, JSF 2.0, and GlassFish v3. The JSF 2.0 classes were obtained from the NetBeans JSF 2.0 bundled library.

How to do it...

Customizing the default messages from Message.properties—to accomplish this task we follow two simple steps. We start by creating our own properties file and copy into it the desired entries from Messages.properties. After that, we modify the entries accordingly to our needs (actually, we leave the property names as default and we modify their values). For example, we have created a properties file named MyMessages.properties as shown next:

javax.faces.component.UIInput.REQUIRED={0}: Value is required - custom message.
javax.faces.validator.LongRangeValidator.NOT_IN_RANGE={2}: Specified attribute is not between the expected values of {0} and {1} - custom message.
javax.faces.validator.LengthValidator.MAXIMUM={1}: Value is greater than allowable maximum of ''{0}''- custom message
javax.faces.validator.LengthValidator.MINIMUM={1}: Value is less than allowable minimum of ''{0}''- custom message

Even if we are in JSF 2.0, we need to configure this properties file in faces-config.xml. This can be done as follows:

<application>
<locale-config>
<default-locale>en</default-locale>
</locale-config>
<message-bundle>users.MyMessages</message-bundle>
</application>

Going further, we create our own error message—in this case we can create our own property names in the properties file. For example, we have created the MyMessages.properties next (notice that this time we have a new set of entries—new property names and new values):

NOT_IN_RANGE=ERROR! - The inserted age is not between the accepted interval, [18,50]!
NOT_IN_LENGTH=ERROR! - The inserted name must have a length between 5 and 25 characters!
AGE_REQUIRED=ERROR! - The age value is required!
NAME_REQUIRED=ERROR! - The name value is required!

Next we have to configure this properties file by following these steps:

  1. In the corresponding page use the f:loadBundle tag to indicate the desired properties file (place this tag before the <body> tag of the page). For example:
    <f:loadBundle basename="users.MyMessages" var="msg"/>
    
  2. Use the requiredMessage and validatorMessage attributes (notice that, in the same manner, for converters there is converterMessage) to indicate the corresponding error property name for each UI component. The requiredMessage attribute is used to indicate the error messages that should be displayed when no value was provided for the corresponding UI component (it can be a String or an EL expression and it has meaning when for the same UI component the required attribute is used and set to true). The validatorMessage attribute is used for indicating the error messages that should be displayed when the provided value can't be successfully validated (it can be a String or an EL expression). As per the example, let's suppose that we have a form with two fields representing a user's age and name. The age should be between 18 and 50 (we will apply the LongRangeValidator) and the name length will be between 5 and 25 characters (we will use the LengthValidator). The error messages will be provided by our MyMessages.properties. For this we have the following code:
    <h:head>
    <title>Customize messages for validators</title>
    </h:head>
    <f:loadBundle basename="users.MyMessages" var="msg"/>
    <h:body>
    <h:form id="UserForm">
    <h:outputText value="Insert your age:"/><br />
    <h:inputText id="userAgeID" required="true"
    value="#{userBean.userAge}"
    requiredMessage="#{msg.AGE_REQUIRED}"
    validatorMessage="#{msg.NOT_IN_RANGE}">
    <f:validateLongRange minimum="18" maximum="50"/>
    </h:inputText>
    <h:message showSummary="true" showDetail="false" for="userAgeID"
    style="color: red; text-decoration:overline"/>
    <br />
    <h:outputText value="Insert your first name:"/><br />
    <h:inputText id="userNameID" required="true"
    value="#{userBean.firstName}"
    requiredMessage="#{msg.NAME_REQUIRED}"
    validatorMessage="#{msg.NOT_IN_LENGTH}">
    <f:validateLength minimum="5" maximum="25" />
    </h:inputText>
    <h:message showSummary="true" showDetail="false"
    for="userNameID"
    style="color: red; text-decoration:overline"/>
    <br />
    <h:commandButton id="submit"
    action="response?faces-redirect=true"
    value="Submit"/>
    </h:form>
    </h:body>
    
  3. Configure this properties file in the faces-config.xml. This can be done as shown next:
    <application>
    <locale-config>
    <default-locale>en</default-locale>
    </locale-config>
    <message-bundle>users.MyMessages</message-bundle>
    </application>
    

    Note

    Notice that even if we are using JSF 2.0, we still need the faces-config.xml file. Annotations and the implicit navigation allow us to write an application without needing a faces-config.xml fille. but there are still cases where the configuration file is needed. Localization information, advanced features such as ELResolvers, PhaseListeners, or artifacts that rely on the decorator pattern still require a faces-config.xml file.

How it works...

The main key resides in the configuration made in faces-config.xml. It indicates to JSF that the corresponding error messages should be found in the specified properties file instead of the default one. When the custom properties' names override the default ones, JSF will automatically detect them. When the properties' names are totally new, you can use the requiredMessage and validatorMessage to fit them accordingly to the UI components. Finally, note that the message aspect is customizable through the h:message tag. This tag is related to its UI component through the for attribute, which has the same value as the id attribute of the UI component.

There's more...

In the case of custom converters you can programmatically generate custom errors like this:

FacesMessage message = new FacesMessage();
message.setDetail("error details");
message.setSummary("error summary");
message.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(message);

See also

The code bundled with this book contains a complete example of this recipe. The project can be opened with NetBeans 6.8 and it is named:

  • Customize_error_messages_for_validators_1
  • Customize_error_messages_for_validators_2
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset