Call MVC 3 Client Side Validation Manually for ajax posts Call MVC 3 Client Side Validation Manually for ajax posts jquery jquery

Call MVC 3 Client Side Validation Manually for ajax posts


Try:

//using the form as the jQuery selector (recommended)$('form').submit(function(evt) {    evt.preventDefault();    var $form = $(this);    if($form.valid()) {        //Ajax call here    }});//using the click event on the submit button$('#buttonId').click(function(evt) {    evt.preventDefault();    var $form = $('form');    if($form.valid()) {        //Ajax call here    }});

This should work with jQuery ajax and MSAjax calls. Could also try using http://nuget.org/packages/TakeCommand.js or https://github.com/webadvanced/takeCommand it will automatically handle this for you.


I have been phaffing about with MVC client side validation for days:

Don't use .click use .submit:

$("#MyForm").on('submit',function () {    if($("#MyForm").valid())    {        //Do ajax stuff    }    //Return false regardless of validation to stop form submitting    //prior to ajax doing its thing    return false;});

I'm going add an update to this, consider cancelling the event rather than returning false (or do both):

$("#MyForm").on('submit',function (e) {    if($("#MyForm").valid())    {        //Do ajax stuff    }    e.preventDefault();    //Return false regardless of validation to stop form submitting    //prior to ajax doing its thing    return false;});


At least in my case (MVC 5), it was also necessary to add the following code or else .valid() would always return true:

$(function () {$(document).ajaxComplete(function(event, request, settings){    //re-parse the DOM after Ajax to enable client validation for any new form fields that have it enabled    $.validator.unobtrusive.parse(document);});

});

See http://johnculviner.com/the-unobtrusive-libraries-client-validation-on-ajax-in-asp-net-mvc-3/