Web Form Validation with JBoss RichFaces and Hibernate Validator

February 9th, 2010 by John Turner Leave a reply »

Last month I posted about Building a Dynamic Tree with JBoss RichFaces and Spring Web Flow. Since then, I have received a few requests to demonstrate how to implement validation within the modal dialog. There are several internet resources that already deal with this but none that provide a complete working example so I decided I would do just that.

You can download the source code in the form of a Maven project and follow along.

Hibernate Validator Dependencies

First step is to add the Hibernate Validator dependency to the project pom. I have used Hibernate Validator 4.0.0.GA because it is a JSR 303 compliant implementation.

<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-validator</artifactId>
  <version>4.0.0.GA</version>
  <scope>compile</scope>
</dependency>

Listing 1 : Hibernate Validator Dependency




Annotating the Model Class

JSR 303 allows for the specification of validation constraints via Annotations and\or XML. The Hibernate Validator documentation has recently been updated to include details on specifying the validation.xml if you prefer to use XML.

For this example I am going to use Annotations to specify a ‘Size’ constraint on the name and description properties of the Organisation class. These are basic constraints but they will suffice for demonstration purposes.

package net.thoughtforge.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.validation.constraints.Size;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("prototype")
public class Organisation implements Serializable {

  private static final long serialVersionUID = -2023156931701914562L;

  private List<Organisation> children;
  
  @Size(min=3, max=200, message="Description must be between 3 and 200 characters in length.")
  private String description;
  
  @Size(min=3, max=50, message="Name must be between 3 and 50 characters in length.")
  private String name;

  private Organisation parent;
  
  public void addChild(Organisation child) {
        if (child.getParent() == null || !child.getParent().equals(this)) {
            child.setParent(this);
        }
        
        if (children == null) {
            children = new ArrayList<Organisation>();
        }
        
        if (!children.contains(child)) {
          children.add(child);
        }
  }
  
  public void removeChild(Organisation child) {
        if (child.getParent() != null && child.getParent().equals(this)) {
            child.setParent(null);
        }
        
        if (children != null) {
            children.remove(child);
        }
  }

  public List<Organisation> getChildren() {
    if (children == null) {
      children = new ArrayList<Organisation>();
    }
    
    return Collections.unmodifiableList(children);
  }
  
  public String getDescription() {
    return description;
  }

  public void setDescription(String description) {
    this.description = description;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public Organisation getParent() {
    return parent;
  }

  public void setParent(Organisation parent) {
    this.parent = parent;
  }
}

Listing 2 : Organisation.java



Applying the Constraints

Of course, as annotations do nothing in and of themselves, I need to invoke the validator to apply the constraints. RichFaces provides 3 components that invoke either the Hibernate or JSR 303 bean validator during the JSF ‘Process Validations’ phase.

I wanted to validate the Organisation name and description properties. These are set within the ‘addChildModalPanel’ and updated within the ‘editChildModalPanel’. The validations are applied to each in exactly the same way.

To apply validations to the name and description ‘inputText’ fields I added a child field. Adding this child component results in the validator being invoked during the ‘Process Validations’ phase.

<h:inputText value="#{addChildOrganisation.name}">
  <rich:beanValidator/>
</h:inputText>

Listing 3 : rich:beanValidator



If the validation fails, messages are added to the FacesContext and will be displayed using the component.

<rich:messages>
  <f:facet name="errorMarker">
    <h:panelGroup>
      <h:graphicImage value="/image/error.gif"/>
      <h:outputText value="  "/>
    </h:panelGroup>
  </f:facet>
</rich:messages>

Listing 4 : rich:messages



Displaying Validation Messages within the Modal Dialog

Finally, I needed to keep the Modal Dialog from closing when validation failures occured. This is achieved by modifying the a4j:commandButton as shown below. It is worth highlighting that each has its own and this is very important (as highlighted in the JBoss RichFaces documentation).

<a4j:commandButton action="addChildModalPanelConfirm"
    value="Ok"
    oncomplete="if (#{!facesContext.messages.hasNext()}) {Richfaces.hideModalPanel('addChildModalPanel')};"
    reRender="dynamicTreePanel"
    styleClass="commandButton"/>

Listing 5 : a4j:commandButton



What I ended up with was a really intuitive and responsive UI with appropriate validations. It was an interesting exercise especially due to the intricacies of the component.

1 Star2 Stars3 Stars4 Stars5 Stars6 Stars7 Stars8 Stars9 Stars10 Stars (3 votes, average: 5.67 out of 10)
Loading ... Loading ...
  • Print
  • Digg
  • del.icio.us
  • DZone
  • Reddit
  • Slashdot
  • StumbleUpon
  • Twitter
  • Facebook
  • Technorati
  • email
  • Google Bookmarks
  • LinkedIn
  • Yahoo! Bookmarks
Advertisement

Leave a Reply