Home arrow Tech Thoughts arrow JSF Validator using Hibernate Annotations
JSF Validator using Hibernate Annotations Print E-mail
I am currently working on two JSF projects and recently I tried out the new validation feature of Hibernate 3 using Java 5 Annotations. I really like the idea of annotation based validation and so I started integration the feature into JSF using a custom validator. Download available at: http://www.schmelzer.cc/Downloads/Files/HibernateValidator.zip

The idea to use Annotations for validating data objects follows the idea of defining information only once. So we can use this meta information in all layers of our applications. Hibernate itself can check before it inserts into the database and a UI framework can use the information to validate user input. Following this idea I have tried out to integrate this feature into JSF using a custom JSF validator.

The resulting code looks something like that:

/**
 * Employee generated by hbm2java
 */
public class Employee implements java.io.Serializable {

    // Fields
    @NotNull
    @Range(min = 100000, max = 1000000)
    private Integer persNr;

    @Length(max = 10)
    private String firstName;

    @NotNull
    @Length(min = 5, max = 50)
    private String lastName;

...

and in the JSP file:

        <af:inputText label="Personalnummer:"
            value="#{employeeEdit.employee.persNr}">
            <val:validator />
        </af:inputText>

or with more properties configured:

        <af:inputText label="Eingetragen am:"
            value="#{employeeEdit.employee.entryDate}">
            <val:validator bundle="test" bean="#{employeeEdit.employee}" property="entryDate"/>
        </af:inputText>

 If you do not configure the validator at all, it will take the parents ui component value and it will resolve the last part of the expression as the property to validate. As an alternativ you also can configure the bean and the property to validate. Additionally you can set the bundle base name of the resource bundle to use.

At the moment I do not really take performance issues into concern. so it might be, that the validator is quite slow. In fact this is absolutly no problem in my application context. But feel free to make suggestions for more performant solutions.

One major issue is, that we cannot make NOT-NULL validation because, JSF will not call out validators if no value is entered in the field. So you still have to set the required attribute.

I am appreciating any comments about the Hibernate JSF validator.

Download at: http://www.schmelzer.cc/Downloads/Files/HibernateValidator.zip