title: Unable to @Valid parameters
body: <p>I am using spring MVC 4 and tomcat 7.</p>
  
  <p>I am new in java and have a validation issue (probably binding) for the <code>emailTo</code> parameter which I would like to be validated (in the UI).
  I already spend my and other programmers time but with no success.</p>
  
  <p>BindingResult result is empty for for emailTo but it fails throw exception when it trying to add it to the DB (due to the @NotNull annotation).
  Means, the annotation works fine but the validation not...</p>
  
  <p>The strange thing is that the validation works fine for <code>modifiedSince</code> parameter (@Temporal(TemporalType.TIMESTAMP)) but not for <code>emailTo</code>.</p>
  
  <p>Oracle's table class via hibernate (Task.java under DBLayer project):</p>
  
  <pre><code>    package entities;
  
  import java.text.ParseException;
  import java.util.ArrayList;
  import java.util.Collection;
  import java.util.Date;
  
  import javax.persistence.CascadeType;
  import javax.persistence.Column;
  import javax.persistence.Entity;
  import javax.persistence.EnumType;
  import javax.persistence.Enumerated;
  import javax.persistence.FetchType;
  import javax.persistence.GeneratedValue;
  import javax.persistence.GenerationType;
  import javax.persistence.Id;
  import javax.persistence.Index;
  import javax.persistence.OneToMany;
  import javax.persistence.SequenceGenerator;
  import javax.persistence.Table;
  import javax.persistence.Temporal;
  import javax.persistence.TemporalType;
  import javax.validation.constraints.NotNull;
  
  import org.hibernate.validator.constraints.Email;
  import org.hibernate.validator.constraints.NotEmpty;
  
  import enums.TaskIdentifierType;
  import enums.TaskPriority;
  import enums.TaskStatus;
  import enums.TaskType;
  
  @Entity
  @Table(name="TASK", indexes= {@Index(columnList="TITLE"),
                                @Index(columnList="TYPE"),
                                @Index(columnList="STATUS")})
  @SequenceGenerator(initialValue = 1, name = "taskIdGen", sequenceName = "TaskSequence")
  public class Task {
  
      @Id
      @GeneratedValue(strategy=GenerationType.SEQUENCE)
      @Column(name="TASK_ID")
      private int taskId;
  
      @Column(name="TITLE")
      private String taskTitle;
  
      @Enumerated(EnumType.STRING)
      @Column(name="TYPE")
      private TaskType type;
  
      @Enumerated(EnumType.STRING)
      @Column(name="STATUS")
      private TaskStatus status;
      .
      .
      .   
      @Temporal(TemporalType.TIMESTAMP)
      @Column(name="MODIFIED_SINCE")
      private Date modifiedSince;
      .
      .
      .
      @Column(name="VALID_PHRASE")
      private String validPhrase;
  
      @Email
      @NotNull
      @NotEmpty
      @Column(name="EMAIL_TO")
      private String emailTo;
  
      @Enumerated(EnumType.STRING)
      @Column(name="PRIORITY")
      TaskPriority priority;
  
      @OneToMany(targetEntity=ResultItem.class, mappedBy="task", fetch=FetchType.LAZY, cascade=CascadeType.DETACH)
      private Collection&lt;ResultItem&gt; resultItems;
  
      public Task() throws ParseException{
          timestamp = new Date();
          status = TaskStatus.NEW;
          priority = TaskPriority.NORMAL;
          resultItems = new ArrayList&lt;ResultItem&gt;();  
          identifierType = TaskIdentifierType.TS_ID;
          type = TaskType.DB;
      }
      .
      .
      .
  </code></pre>
  
  <p>TaskController.java under LinkCheckerGUI project:</p>
  
  <pre><code>@RequestMapping(value = "task/new", method = RequestMethod.POST)
      public String processCreationForm(@Valid @ModelAttribute("taskModel")NewTaskModel taskModel, BindingResult result, SessionStatus status) {
          System.out.println("---------in task controller");
  
          if (taskModel == null){
              System.out.println("Task is null");
          }
          else{
              System.out.println("------------task email to=" + taskModel.getTask().getEmailTo().toString());
          }
  
          System.out.println("--------------all Errors:" + result.getFieldErrors());
  
      if (result.hasErrors()) {
              for(ObjectError oe : result.getAllErrors()){
                  System.out.println("-----------------error:"+oe.toString());    
      }
              System.out.println("-------Error found in new task values");/////////////////
              return "task/newTask";
          } 
  
          try {
  
              taskManager.addTask(taskModel.getTask());
          } catch (Exception e) {
              System.out.println("Exception: " + e);
          }
          return "redirect:new";
      }
  </code></pre>
  
  <p>newTask.jsp under LinkCheckerGUI project:</p>
  
  <pre><code>    &lt;%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%&gt;
      &lt;%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt"%&gt;
      &lt;%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%&gt;
      &lt;%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%&gt;
      &lt;%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%&gt;
  
      &lt;html lang="en"&gt;
      &lt;head&gt;
      &lt;meta 
  
  http-equiv="Content-Type" content="text/html; charset=windows-1255"&gt;
      &lt;title&gt;LinkChecker&lt;/title&gt;
      &lt;/head&gt;
      &lt;%-- &lt;jsp:include page="headersMenu.jsp"/&gt; --%&gt;
      &lt;jsp:include page="../fragments/staticFiles.jsp"/&gt;
      &lt;body&gt;
      &lt;h2&gt;&lt;fmt:message key="task.add.title"/&gt;&lt;/h2&gt;
      &lt;div class="container"&gt;
      &lt;jsp:include page="../fragments/bodyHeader.jsp"/&gt;
      &lt;form:form modelAttribute="taskModel" method="POST"&gt;
          &lt;table&gt;
          &lt;tr&gt;
              &lt;td&gt;&lt;form:label path="task.taskTitle"/&gt;Task name:&lt;/td&gt;  
                  &lt;td&gt;&lt;form:input path="task.taskTitle"/&gt;&lt;/td&gt;
              &lt;/tr&gt; 
  
              &lt;tr&gt;
              &lt;td&gt;&lt;form:label path="task.invalidPhrase"/&gt;Invalid Phrase:&lt;/td&gt;  
                  &lt;td&gt;&lt;form:input path="task.invalidPhrase"/&gt;&lt;/td&gt;
              &lt;/tr&gt;
          .
          .
          . 
              &lt;tr&gt;
              &lt;td&gt;&lt;form:label path="task.validPhrase"/&gt;Valid Phrase:&lt;/td&gt;  
                  &lt;td&gt;&lt;form:input path="task.validPhrase"/&gt;&lt;/td&gt;
              &lt;/tr&gt; 
              &lt;tr&gt;
              &lt;td&gt;&lt;form:label path="task.modifiedSince" class="validationError"/&gt;Modified Since:&lt;/td&gt;  
                  &lt;td&gt;&lt;form:input path="task.modifiedSince"/&gt;&lt;/td&gt;
                  &lt;td&gt;&lt;form:errors path="task.modifiedSince" cssClass="validationError"/&gt;&lt;/td&gt;
              &lt;/tr&gt;
              .
              .
              .
              &lt;tr&gt;
                  &lt;td&gt;&lt;/td&gt;
                  &lt;td style="color: red; font-weight: bold;"&gt;&lt;form:label path="task.emailTo"/&gt;Email To:&lt;/td&gt;  
                  &lt;td class="validationError"&gt;&lt;form:label path="task.emailTo"/&gt;Email To:&lt;/td&gt;  
                  &lt;td&gt;&lt;form:input path="task.emailTo"/&gt;&lt;/td&gt;
                  &lt;td&gt;&lt;form:errors path="task.emailTo" cssClass="validationError"/&gt;&lt;/td&gt;
              &lt;/tr&gt;
          &lt;/table&gt;
  
                  &lt;input type="submit" id="submit" value="Submit"/&gt;
      &lt;/form:form&gt;
      &lt;/div&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>This is the relevant code from my two related projects (DBLayer and LinkCheckerGUI).</p>
  
  <p>In this case, after clicking on 'submit':</p>
  
  <ol>
  <li><blockquote>
    <p>In the form, I get the requested validation message for the "Modified Since" field (I left it empty were it's definition is @Temporal(TemporalType.TIMESTAMP) ).</p>
  </blockquote></li>
  <li><p>output:</p></li>
  </ol>
  
  <blockquote>
    <p>all Errors:[Field error in object 'taskModel' on field 'task.modifiedSince': rejected value []; codes [typeMismatch.taskModel.task.modifiedSince,typeMismatch.task.modifiedSince,typeMismatch.modifiedSince,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [taskModel.task.modifiedSince,task.modifiedSince]; arguments []; default message [task.modifiedSince]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'task.modifiedSince'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type @javax.persistence.Temporal @javax.persistence.Column java.util.Date for value ''; nested exception is java.lang.IllegalArgumentException]]
    -----------------error:Field error in object 'taskModel' on field 'task.modifiedSince': rejected value []; codes [typeMismatch.taskModel.task.modifiedSince,typeMismatch.task.modifiedSince,typeMismatch.modifiedSince,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [taskModel.task.modifiedSince,task.modifiedSince]; arguments []; default message [task.modifiedSince]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'task.modifiedSince'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type @javax.persistence.Temporal @javax.persistence.Column java.util.Date for value ''; nested exception is java.lang.IllegalArgumentException]
    -------Error found in new task values</p>
  </blockquote>
  
  <ol start="3">
  <li><blockquote>
    <p>No other validation failure, although emailTo should fail because I left it empty as well.</p>
  </blockquote></li>
  </ol>
  
  <p>When adding the binding (in the taskController.java):</p>
  
  <pre><code>@InitBinder
  public void initBinder(WebDataBinder binder) {
      //This WebDataBinder set the Date parameters to null in case they are empty
      SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
      dateFormat.setLenient(false);
  
      // true passed to CustomDateEditor constructor means convert empty String to null
      binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
  }
  </code></pre>
  
  <p>The validation message for <code>modifiedSince</code> disappeared as expected and no other message displayed and the output is:</p>
  
  <blockquote>
    <p>------------task email to= --------------all Errors:[]</p>
  </blockquote>
  
  <p>Means, results doesn't hold any error (for the emailTo parameter).</p>
  
  <p>If I'll remove the try/catch from the controller (for addTask method) it will crush (throw exception) because the emailTo parameter is empty and it's unable to add it to the DB (as expected).</p>
  
  <p>****I created a simple class and it works fine. Is there a reason why it doesn't work Entity class?<strong>?</strong></p>
  
  <p>I would appreciate your assist here...</p>
  
  <p>Thanks in advance!</p>
  
  <p>Mike</p>