Monday, February 21, 2011

Error messages for required fields in JSF 1.2

JSF 1.1

When you have required fields in your JSF page, you simple add the required="true" attribute to the inputField and the user will get error message when user the field the field blank.
<h:inputText id="accountnumber" value="#{accountSetting.accountNumber}"
  required="true" />
This is all great, since we don't have to do much as a developer. However, the user gets an ugly error message: "accountForm:accountnumber: Validation Error: Value is required." This message is customizable by overriding this message in your message bundle and is pretty limited in how customized you want it to be.

JSF 1.2

JSF 1.2 and later makes it easier to create custom error messages for required fields, just add the requiredMessage attribute:
<h:inputText id="accountnumber" value="#{accountSetting.accountNumber}"
  required="true" requiredMessage="Account number is required" />
When the user has forgotten to enter something in this field, the JSF framework will display the error message supplied with the requiredMessage attribute. To supply translations for different languages, you can put the message in a resource bundle. Note that you must configure this resource bundle in faces-config.xml like this:
<application>
  <!-- ... -->
  <resource-bundle>
    <base-name>com.example.messages</base-name>
  <var>bundle</var>
  </resource-bundle>
</application>
This makes it possible to use the configured variable "bundle" anywhere in your pages, including the requiredMessage:
<h:inputText id="accountnumber" value="#{accountSetting.accountNumber}"
  required="true" requiredMessage="#{bundle.error_required_accountNumber}" />
I have found that the old way of using the loadBundle JSF component does not work with requiredMessage. The configured resource-bundle in faces-config.xml is much neater anyway.