Validating forms with RichFaces rich:ajaxValidator

The rich:ajaxValidator is a component designed to provide validation using Hibernate model-based constraints and AJAX mechanism (details about Hibernate Validator can be found at https://www.hibernate.org/412.html). In this recipe, we will validate a simple form made of two fields representing the e-mail address and age of a user.

Getting ready

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. In addition, we have used RichFaces 3.3.3.BETA1, which provide support for JSF 2.0. You can download this distribution from http://www.jboss.org/richfaces. The RichFaces libraries (including necessary dependencies) are in the book code bundle, under the /JSF_libs/RichFaces JSF 2.0 folder.

How to do it...

The rich:ajaxValidator tag is usually nested in a UI Component, such as h:inputText. The most important attribute of this tag is the event attribute. Its value indicates the event that should happen before the validation takes place. As per the example, the onkeyup event will validate the corresponding input every time a key is pressed and released (this is possible thanks to the AJAX mechanism). Here is an example:

<h:form id="form">
<h:panelGrid columns="3">
<h:outputLabel for="email" value="Email Address:" />
<h:inputText id="email" value="#{bean.email}" label="Email">
<rich:ajaxValidator event="onkeyup"
summary="Invalid Email address"/>
</h:inputText>
<rich:message for="email"/>
<h:outputLabel for="age" value="Age:" />
<h:inputText id="age" value="#{bean.age}" label="Age">
<rich:ajaxValidator event="onkeyup"
summary="Invalid age, must be between 18 and 90"/>
</h:inputText>
<rich:message for="age"/>
</h:panelGrid>
<h:commandButton value="Submit"></h:commandButton>
<rich:messages/>
</h:form>

The validator restrictions are specified in Hibernate validator style using the corresponding annotations in a bean. In our example, the Bean bean is the one from listing Bean.java, in the previous recipe.

How it works...

This time the validator restrictions are taken directly from the bean, instead of using dedicated attributes inside the validator tag. In addition, the AJAX mechanism allows JSF to accomplish the validation tasks without submitting the form.

See also

The code bundled with this book contains a complete example of this recipe. The project can be opened with NetBeans 6.8 and it is named: Validate_forms_with_RichFaces_ajaxValidator.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset