ASP.Net MVC Ajax form with jQuery validation
- by Tomas Lycken
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 jQuery Validation plugin. I get the plugin to highlight the inputs with invalid input data, but despite the invalid input the form is posted to the server.
How do I stop this, and make sure that the data is only posted when the form validates?
My code
The form:
<fieldset>
<legend>leave a message</legend>
<% using (Ajax.BeginForm("Post", new AjaxOptions
{
UpdateTargetId = "GBPostList",
InsertionMode = InsertionMode.InsertBefore,
OnSuccess = "getGbPostSuccess",
OnFailure = "showFaliure"
}))
{ %>
<div class="column" style="width: 230px;">
<p>
<label for="Post.Header">
Rubrik</label>
<%= Html.TextBox("Post.Header", null, new { @style = "width: 200px;", @class="text required" }) %></p>
<p>
<label for="Post.Post">
Meddelande</label>
<%= Html.TextArea("Post.Post", new { @style = "width: 230px; height: 120px;" }) %></p>
</div>
<p>
<input type="submit" value="OK!" /></p>
</fieldset>
The JavaScript validation:
$(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();
});
EDIT: As I was getting downvotes for publishing follow-up problems and their solutions in answers, here is also the working validate method...
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();
}