HTML and CSS Reference
In-Depth Information
We already have seen examples of <f:validateRequired> and <f:validateLongRange> validators in Listing 3-11.
<f:validateDoubleRange> is the same as the <f:validateLongRange> ; however, it works with Double instead of
Long. <f:validateLength> validator is used to validate that the EditableValueHolder value is within the specified
length range. For example:
<h:inputText id="address"
required="true"
value="#{person.address}">
<f:validateLength minimum="20" maximum="120"/>
</h:inputText>
As shown in this example, the address attribute of person managed bean is validated to have a length of
minimum 20 and maximum 120 characters using the <f:validateLength> validator in the "address" input text.
<f:validateRegex> validator is used to validate that the EditableValueHolder value is complaint with a
specified Java regular expression.
<h:inputText id="email"
required="true"
value="#{person.email}">
<f:validateRegex pattern="(.+@.+\.[a-zA-Z]+)?"/>
</h:inputText>
As shown in this example, the email attribute of person managed bean is validated to have a valid e-mail using
the "(.+@.+\.[a-zA-Z]+)?" regular expression in the pattern field of the <f:validateRegex> validator for the
"email" input text.
<f:validateBean> validator is used to assign the EditableValueHolder local value validation to the Java Bean
Validation APIs (JSR 303). We will go into the details of this validator in the “JSR 303 Bean Validation with JSF” section.
You can override validation messages by using either the requiredMessage attribute of the
EditableValueHolder s for the required field validation error message or the validatorMessage attribute for general
validation error messages on the EditableValueHolder . For example:
<h:inputText id="someNumber"
value="#{bean.someNumber}"
required="true"
requiredMessage="You have to enter a number"
validatorMessage="Number has to be minimum 10 and maximum 100">
<f:validateLongRange minimum="10" maximum="100"/>
</h:inputText>
This will show a required field validation error message, “You have to enter a number,” if the user does not enter a
value in the input text, and will show a validation message, “Number has to be minimum 10 and maximum 100”, if the
user enters a number that is out of the range (less than 10 or greater than 100).
Building Custom JSF Validator
Adding to all of the mentioned built-in validators provided by the JSF framework, JSF allows the developers to create
their own custom validators. Let's see an example to illustrate this. Assume we want to have an EmailValidator
custom validator which validates that the user input is complaint with an e-mail format.
In order to implement our EmailValidator custom validator, we need to extend the Validator interface and
implement validate method. Listing 3-12 shows the EmailValidator implementation.
 
Search WWH ::




Custom Search