How to in ASP.NET MVC prevent jquery ajax submit if validation fails How to in ASP.NET MVC prevent jquery ajax submit if validation fails ajax ajax

How to in ASP.NET MVC prevent jquery ajax submit if validation fails


You need to conditionally make the ajax call only if the form is valid, which can be done with this javascript code:

if ($("#form1").valid()) {    // make the ajax call}

The documentation is here: .valid().

Please, verify that the form's id in the generated page is indeed form1. If not, there are alternative selectors that you can use, or ways to get the id which will be generated by the Razor code.

NOTE: as I reread your code I can see you're using a single handler for all forms. In that case you must call the .valid() method in the form that triggered the event, which sill be available trhough $(this). I.e, do $(this).valid() to check if the form is valid.


The proper way to use ajax with this plugin is to put the ajax inside of the plugin's submitHandler callback function.

"The right place to submit a form via Ajax after it is validated."

From documentation

Example: Submits the form via Ajax when valid.

$(".selector").validate({  submitHandler: function(form) {    $(form).ajaxSubmit();  }});

This ensures that if the form is valid then only form is submited.


First dont use e.preventDefault(); it will Prevent a submit button from submitting a form.

In your $(".allforms").submit function first validate your form

like this var frmVlalidation = $('#formId').valid();

if your form is validated properly frmVlalidation value will be true if validation fails it will return false .

by using this variable call ajax.

like this.

$(".allforms").submit(function (e) {        var frmVlalidation = $('#formId').valid();        if (frmVlalidation == true)         {        var self = this;        $.ajax({            processData: false,            contentType: false,            data: new FormData(this),            type: $(this).attr('method'),            url: $(this).attr('action'),            success: function (data) {                //other logic            }        });       }        return (false);    });