The Java EE 6 Tutorial

Validating Contact Input from a JavaServer Faces Application

The address-book application uses a JavaServer Faces web front end to allow users to enter contacts. While JavaServer Faces has a form input validation mechanism using tags in Facelets XHTML files, address-book doesn’t use these validation tags. Bean Validation constraints in JavaServer Faces backing beans, in this case in the Contact entity, automatically trigger validation when the forms are submitted.

The following code snippet from the Create.xhtml Facelets file shows some of the input form for creating new Contact instances:

<h:form>
    <h:panelGrid columns="3">
        <h:outputLabel value="#{bundle.CreateContactLabel_firstName}" 
                       for="firstName" />
        <h:inputText id="firstName" 
                     value="#{contactController.selected.firstName}" 
                     title="#{bundle.CreateContactTitle_firstName}" />
        <h:message for="firstName" 
                   errorStyle="color: red" 
                   infoStyle="color: green" />
        <h:outputLabel value="#{bundle.CreateContactLabel_lastName}" 
                       for="lastName" />
        <h:inputText id="lastName" 
                     value="#{contactController.selected.lastName}" 
                     title="#{bundle.CreateContactTitle_lastName}" />
        <h:message for="lastName" 
                   errorStyle="color: red" 
                   infoStyle="color: green" />
        ...
    </h:panelGrid>
</h:form>

The <h:inputText> tags firstName and lastName are bound to the attributes in the Contact entity instance selected in the ContactController stateless session bean. Each <h:inputText> tag has an associated <h:message> tag that will display validation error messages. The form doesn’t require any JavaServer Faces validation tags, however.