Saturday, December 1, 2012

How to use rich:beanValidator together with Hibernate annotations to validate input components

<rich:beanValidator/> component from Richfaces is very useful because it lets us validate input components by using Hibernate annotations. This highly reduces our need of writing validator classes.

This tutorial will show you how to use this component with @NotNull annotation to avoid NULL inputs and to display a custom message.

Create a JSF managed bean or a SEAM component as below.
public class MyBean {
  Integer number;
  
  @NotNull(message = "Please enter a value")
  public Integer getNumber() {
    return number;
  }

  public void setNumber(Integer number) {
    this.number = number;
  }
}

You need to add this import.
import org.hibernate.validator.NotNull;

This is your xhtml page.
<h:form>
  <h:inputText value="#{myBean.number}" id="txtNumber">
    <rich:beanValidator/>
  </h:inputText>
  <rich:message for="txtNumber"/>
  <a4j:commandButton value="Submit"/>
</h:form>

In this page we have a <h:inputText>  component. inside it we have a <rich:beanValidator/> component. What that component does is when the user enters a value and click the button that value is validated according to the hibernate annotations in the bean class. In this example since we have used the @NotNull annotation, the value is checked for null. If the value is null then our message "Please enter a value" is displayed in the <rich:message> component.

Similarly toy can use <rich:beanValidator/> component with other Hibernate validator annotations.

✔  You can find a list of validator annotations here

    If your page contains lot of input components you would have to put <rich:beanValidator/>s inside each of them. But it could be painful. So Richfaces introduces another component for this. It is <rich:graphValidator/> component. Instead of using <rich:beanValidator/>s inside each element, you can get the same result by wrapping all the input elements with only one <rich:graphValidator/> as below.


<h:form>
  
  <rich:graphValidator>
    <h:inputText value="#{myBean.number}" id="num" />
    <rich:message for="num" /><br />

    <rich:calendar value="#{myBean.date}" id="dte" />
    <rich:message for="dte" /><br/>
     </rich:graphValidator>

  <a4j:commandButton value="Save" />
</h:form>

No comments:

Post a Comment