JSF doesn’t validate empty forms

Error:

Caused by org.hibernate.validator.InvalidStateException with message: “validation failed for: MyHibernateEntity”

Are you getting this error while trying to validate a form with empty fields using Seam, JSF and Hibernate? Then read on.

Seam allows you to define validation conditions on a single place: on the Hibernate / JPA entities. And then use this condition in the view without duplicating them.
Sounds nice, but when you try it in practice, you can easily run into the “validation failed” error above.

The problem is caused by JSF. It sounds idiot (and it is), but JSF validators aren’t invoked on empty fields. So the following code already causes the error when submitting an empty comment field

<h:inputTextarea id="comment" value="#{user.comment}" cols="10" rows="3">
   <s:validate/>
</h:inputTextarea>
<h:message for="comment" />
@Entity
public class User {
  // ....

  @NotNull
  private String comment;

  // ....
}

Fortunately a solution is simple, set the required attribute of the input field element to true. Like this:

<h:inputTextarea id="comment" value="#{user.comment}" cols="10" rows="3" required="true">

More info:
http://jamiemcilroy.wordpress.com/2006/10/10/not-quite-what-i-expectedjsf-validation/
http://forum.java.sun.com/thread.jspa?threadID=5055877
http://www.jboss.com/index.html?module=bb&op=viewtopic&t=127793

Tags: ,

One Response to “JSF doesn’t validate empty forms”

  1. Benny's Blog Says:

    Parameterized JSF Facelets Validators…

    Parameterizable validators are a tricky thing; they need to be represented in various configuration files and on top of that need to be stateful. Read on to find out how you can use validator tags with custom attributes.
    ……

Leave a Reply