title: ASP.Net MVC Ajax form with jQuery validation
body: <p>I have an MVC view with a form built with the Ajax.BeginForm() helper method, and I'm trying to validate user input with the <a href="http://docs.jquery.com/plugins/validation" rel="noreferrer" title="jQuery Validation plugin">jQuery Validation plugin</a>. I get the plugin to highlight the inputs with invalid input data, but despite the invalid input the form is posted to the server.</p>
  
  <p>How do I stop this, and make sure that the data is only posted when the form validates?</p>
  
  <p>My code</p>
  
  <hr>
  
  <p>The form:</p>
  
  <pre><code>&lt;fieldset&gt;
      &lt;legend&gt;leave a message&lt;/legend&gt;
          &lt;% using (Ajax.BeginForm("Post", new AjaxOptions
             {
                 UpdateTargetId = "GBPostList",
                 InsertionMode = InsertionMode.InsertBefore,
                 OnSuccess = "getGbPostSuccess",
                 OnFailure = "showFaliure"
             }))
             { %&gt;
          &lt;div class="column" style="width: 230px;"&gt;
              &lt;p&gt;
                  &lt;label for="Post.Header"&gt;
                      Rubrik&lt;/label&gt;
                  &lt;%= Html.TextBox("Post.Header", null, new { @style = "width: 200px;", @class="text required" }) %&gt;&lt;/p&gt;
              &lt;p&gt;
                  &lt;label for="Post.Post"&gt;
                      Meddelande&lt;/label&gt;
                  &lt;%= Html.TextArea("Post.Post", new { @style = "width: 230px; height: 120px;" }) %&gt;&lt;/p&gt;
          &lt;/div&gt;
          &lt;p&gt;
              &lt;input type="submit" value="OK!" /&gt;&lt;/p&gt;
      &lt;/fieldset&gt;
  </code></pre>
  
  <hr>
  
  <p>The JavaScript validation:</p>
  
  <pre><code>$(document).ready(function() {
      // for highlight
      var elements = $("input[type!='submit'], textarea, select");
      elements.focus(function() {
          $(this).parents('p').addClass('highlight');
      });
      elements.blur(function() {
          $(this).parents('p').removeClass('highlight');
      });
  
      // for validation
      $("form").validate();   
  });
  </code></pre>
  
  <p><strong>EDIT:</strong> As I was getting downvotes for publishing follow-up problems and their solutions in answers, here is also the working validate method...</p>
  
  <pre><code>function ajaxValidate() {
      return $('form').validate({
      rules: {
          "Post.Header": { required: true },
          "Post.Post": { required: true, minlength: 3 }
      },
      messages: {
          "Post.Header": "Please enter a header",
          "Post.Post": {
              required: "Please enter a message",
              minlength: "Your message must be 3 characters long"
              }
          }
      }).form();
  }
  </code></pre>