Hi all,
The problem I'm having is that my Bean Validation isn't working as I would expect.
I have a Session Scoped Managed Bean with a name
field that is bound to an h:inputText
. The name must be entered, and have a minimum length of 1 character, and a maximum length of 5 characters. I expect that when I enter the name into the textbox, it will be validated accordingly by the backing bean, and if it fails, then it would display the corresponding error messages.
However, this is not the case. The validations are always failing, even if I enter a valid case in the inputText (e.g. "abc"). On debugging the application, it seems that the getName()
accessor is always called, and the setter is never reached. Am I doing something wrong? I assume the validator uses the accessor to validate, but the problem is that the setter never gets a chance to update the value of the name... I must be missing something.
Below is the Managed Bean:
@ManagedBean
@SessionScoped
public class James implements Serializable {
public James() {
super();
}
private String name;
@NotNull
@Min(value = 1)
@Max(value = 5)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Below is the fragment of the JSF xhtml. I tried a few different variations with separate forms, but the first option is the one I would assume to work (I think it's equivalent to the third option, but tried just in case :) )
<h:messages/>
<h:form>
<h:inputText id="jamesName" value="#{james.name}"/>
<h:message for="jamesName"/>
<h:commandButton value="submit"/>
</h:form>
<h:form>
<h:inputText id="jamesName" value="#{james.name}" immediate="true"/>
<h:message for="jamesName"/>
<h:commandButton value="submit"/>
</h:form>
<h:form>
<h:inputText id="jamesName" value="#{james.name}">
<f:validateBean />
</h:inputText>
<h:message for="jamesName"/>
<h:commandButton value="submit"/>
</h:form>
I'm using JSF 2.0.2-FCS with Hibernate Entity Manager 3.3.2.GA and Hibernate Validator 4.0.2.GA (below are the relevant parts from my Maven POM), running in Tomcat 6.0.20 on Windows XP Pro Service Pack 3 (32-bit).
<dependency>
<groupId>javax.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.0.2-FCS</version>
</dependency>
<dependency>
<groupId>javax.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.0.2-FCS</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.3.2.GA</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.0.2.GA</version>
</dependency>