Optional and empty fields are validated
cardel.ka.jelinek.seznam.cz Apr 27, 2008 3:46 PMHi,
I am using Seam 2.0.1 GA, JSF 1.2 and Hibernate 3.2.4
In my application I am using @Email and @Length annotations on my User entity:
@Entity @Table(name = "users") public class User implements Serializable { private String email; private String city; @Email public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Length(min=2,max=25) public String getCity() { return city; } public void setCity(String city) { this.city = city; }
It is working fine. When field with email or city has incorrect form, validation message is showed. But if I am keep these fields empty, then I am getting Hibernate exception:
org.hibernate.validator.InvalidStateException: validation failed for: hcp.User
But this fields has to be optional. I read somewhere, that validation is made only if fields in JSF are not empty. But in my case, validation is fired every time.
In JSF form I am using s:validate tag. Fields are set as no required.
<h:outputLabel for="emailInput">Email</h:outputLabel> <a:outputPanel id="emailPanel"> <s:decorate> <h:inputText id="emailInput" value="#{user.email}" styleClass="text" > <a:support event="onblur" reRender="emailPanel" ajaxSingle="true" /> <s:validate /> </h:inputText> <h:message for="emailInput" errorClass="error" /> </s:decorate> </a:outputPanel> <h:outputLabel for="cityInput">City</h:outputLabel> <a:outputPanel id="cityPanel"> <s:decorate> <h:inputText id="cityInput" value="#{user.city}" styleClass="text" > <a:support event="onblur" reRender="cityPanel" ajaxSingle="true" /> <s:validate /> </h:inputText> <h:message for="cityInput" errorClass="error" /> </s:decorate> </a:outputPanel>
I solved storing null email value to DB with this 'hack' before persisting.
if (this.getEmail().equalsIgnoreCase("")) this.setEmail(null);
But then I found out, that the same problem is with all optional fields, that have some hibernate validation tag.
Any help or hint how to use optional fields with validation?