Using the standard JSF validators can be a simple task if you keep in mind two simple observations:
validator
attribute or by nesting JSF-provided tagsUIInput
components or components whose classes extend UIInput
In this recipe, you will see how to use the JSF standard validators listed next:
LengthValidator
: Counts the number of characters of a value and checks if it fits in a given range. The range boundaries are given by two attributes, as follows:minimum
: The minimum acceptable number of charactersmaximum
: The maximum acceptable number of charactersLongRangeValidator
: Attempts to convert the value to a number of Java long
primitive type and checks to see if that number fits in a given range. The range boundaries are given by two attributes, as follows:minimum
: The minimum acceptable numbermaximum
: The maximum acceptable numberIf these attributes are skipped, then the validator only checks if the value is numeric.
If these attributes are skipped, then the validator will only check if the value is numeric.
In this recipe, you will see how to use the first two previous validators.
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.
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
). Now, the corresponding form will look like this:
<h:form id="UserForm"> <h:outputText value="Insert your age:"/><br /> <h:inputText id="userAgeID" required="true" value="#{userBean.userAge}"> <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}"> <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>