title: Spring Form Ajax Request + Hibernate Validation
body: <p>I always used <code>@Valid</code> and a <code>BindingResult</code> to validate form fields.
  Now using Ajax, based on <a href="http://blog.springsource.org/2010/01/25/ajax-simplifications-in-spring-3-0/" rel="nofollow">this</a> article, it's not possible to use <code>BindingResult</code> instead of or additional to <code>HttpServletResponse</code> because this would result in a Bad Request (HTTP Error Code 400).</p>
  
  <p>How to validate my form fields now?</p>
  
  <pre><code>  @RequestMapping( value = "/save.html", params = "json", method = RequestMethod.POST )
    public @ResponseBody Map&lt;String, ? extends Object&gt; saveJSON( @RequestBody Location location, /* BindingResult result, */ HttpServletResponse response )
    {
      return Collections.singletonMap( "foo", "foobar" );
    }
  </code></pre>
  
  <p>This was the old way without ajax:</p>
  
  <pre><code>  @RequestMapping( value = "/save.html", method = RequestMethod.POST )
    public String save( @ModelAttribute( "location" ) @Valid Location location, BindingResult result, Map&lt;String, Object&gt; map )
    {
      Location l;
      if ( ( l = service.findByTitle( location.getTitle() ) ) != null )
      {
        if ( location.getId() != l.getId() )
        {
          result.addError( new FieldError( "location", "title", messageSource.getMessage( "Unique.location.title", null, null ) ) );
        }
      }
  
      if ( result.hasErrors() )
      {
        return "locationform";
      }
  
      service.save( location );
      return "redirect:/locations/index.html";
    }
  </code></pre>
  
  <p><strong>EDIT</strong></p>
  
  <p>Tried this, but there's no <code>errors</code> member in result which contains <code>true</code> when leaving form unfilled (this should cause a @NotEmpty Constraint message)</p>
  
  <pre><code>  @RequestMapping( value = "/save.html", params = "json", method = RequestMethod.POST )
    public @ResponseBody Map&lt;String, ? extends Object&gt; saveJSON( @RequestBody Location location, HttpServletResponse response, Map&lt;String, Object&gt; map )
    {
      BindingResult result = new BeanPropertyBindingResult( location, "" );
      if ( result.hasErrors() ) map.put( "errors", true );
      map.put( "foo", "foobar" );
      return map;
    }
  </code></pre>