<?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core"> <h:head> <title>Required Input</title> <style type="text/css"> .label { text-align: right; } .input { border: thin solid blue; } .error { color: red; } </style> </h:head> <h:body> <h2>Required Input - Index Page</h2> <h:form> <h:panelGrid columns="3" columnClasses="label,input,error"> <h:outputText value="Text"/> <h:inputText id="text" value="#{data.text}" required="true" requiredMessage="Text is required."/> <h:message for="text"/> <h:outputText value="Selection"/> <h:selectOneListbox id="selection" value="#{data.selection}" required="true" requiredMessage="Selection is required."> <f:selectItem itemValue="item1" itemLabel="item1"/> <f:selectItem itemValue="item2" itemLabel="item2"/> <f:selectItem itemValue="item3" itemLabel="item3"/> <f:selectItem itemValue="item4" itemLabel="item4"/> </h:selectOneListbox> <h:message for="selection"/> </h:panelGrid> <p> You will not get anywhere clicking the button below until the required text has been filled in and the required section is made. </p> <h:commandButton value="Go to Success Page" action="success-page"/> </h:form> <h:form> <p> The button below takes you to another JSF page without requiring that you fill in the information above. This is accomplished by putting it in a separate <h:form> tag. </p> <h:commandButton value="Go to Another Page" action="another-page"/> </h:form> </h:body> </html>
All of the required input handling occurs in the first <h:form> tag of index.xhtml. Both the <h:inputText> and the <h:selectOneListbox> tags are modified in 3 ways:
A <h:panelGrid> with 3 columns is used to lay out three display columns:
The error messages for the input widgets are obtained with the <h:message> tags. The for attribute value specifies the id of the widget whose error message should be displayed.
The user has a alternative to filling in the first <h:form> tag: she can click on the "Go to Success Page" button which is in the second <h:form> tag.
When a user clicks on a command button, the browser only sends form data within the same form. Since the form containg the "Go to Success Page" button has no input widgets there is no input information sent to the application server. Thus the user does not get error messages about missing information.