Using the Standard Validators
JavaServer Faces technology provides a set of standard classes and associated tags that page authors and application developers can use to validate a component's data. Table 18-7 lists all the standard validator classes and the tags that allow you to use the validators from the page.
All these validator classes implement the
Validatorinterface. Component writers and application developers can also implement this interface to define their own set of constraints for a component's value.When using the standard
Validatorimplementations, you don't need to write any code to perform validation. You simply nest the standard validator tag of your choice inside a tag that represents a component of type UIInput (or a subclass ofUIInput) and provide the necessary constraints, if the tag requires it. Validation can be performed only onUIInputcomponents or components whose classes extendUIInputbecause these components accept values that can be validated.This section shows you how to use the standard
Validatorimplementations.See The UIMessage and UIMessages Components for information on how to display validation error messages on the page.
Requiring a Value
The
nameinputTexttag on thebookcashier.jsppage has arequiredattribute, which is set totrue. Because of this, the JavaServer Faces implementation checks whether the value of the component is null or is an empty String.If your component must have a non-
nullvalue or aStringvalue at least one character in length, you should add arequiredattribute to your component tag and set it totrue. If your tag does have arequiredattribute that is set totrueand the value isnullor a zero-length string, no other validators registered on the tag are called. If your tag does not have arequiredattribute set totrue, other validators registered on the tag are called, but those validators must handle the possibility of anullor zero-length string.Here is the
nameinputTexttag:Using the LongRangeValidator
The Duke's Bookstore application uses a
validateLongRangetag on thequantityinput field of thebookshowcart.jsppage:<h:inputText id="quantity" size="4" value="#{item.quantity}"> <f:validateLongRange minimum="1"/> </h:inputText> <h:message for="quantity"/>This tag requires that the user enter a number that is at least 1. The
sizeattribute specifies that the number can have no more than four digits. ThevalidateLongRangetag also has amaximumattribute, with which you can set a maximum value of the input.The attributes of all the standard validator tags are value-binding-enabled. This means that the attributes can reference backing bean properties rather than specify literal values. For example, the
validateLongRangetag in the preceding example can reference a backing bean property calledminimumto get the minimum value acceptable to the validator implementation: