Jquery – how to stop postback or submit event for jQuery Unobtrusive validation

asp.net-mvcasp.net-mvc-4jqueryjquery-validateunobtrusive-validation

I am using jQuery Unobtrusive Validation and want to do few things before I submit the form.
I dont want to postback the form after successful validation, but instead want to show a success message to user and reset the same form for adding another data.

in the following code, it shows me alert only when form is not valid, if its valid it just do a postback.

Currently my form gets submitted even though I want to avoid postback in this scenario.

@model MyProject.ViewModels.CustomerViewModel

<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>

<script type="text/javascript">
$(document).ready(function () {

    $("#addCustomer").click(function () {

        $("#myForm").validate();

        if ($("#myForm").valid()) {

            // This part doesn't get triggered

            alert('yes valid');
            //$.post(...post my data using ajax..)
            alert('data posted successfully.');
            //clear form to submit another data
            clearForm();
            return false;
        }
        else{
            alert('no not valid');
            return false;
        }

  <form id="myForm">
    <div class="formPanel">
            <label>Display Name</label>
            @Html.EditorFor(model => model.CustomerName)
            @Html.ValidationMessageFor(model => model.CustomerName)
    </div>
   <button class="btn btn-primary" id="addCustomer">Save</button>
  </div>
 </form>

Best Answer

By default, the submit event is always blocked by jQuery Validate on an invalid form. If that's not happening, then you're not using the plugin properly.


You misunderstand the .validate() method...

$(document).ready(function () {

    $("#addCustomer").click(function () {

        $("#myForm").validate();

        if ($("#myForm").valid()) {
        ....

The .validate() method is only used for initializing the plugin on your form and never gets called within a click handler. It gets called once within the DOM ready event handler and by default the click of a type="submit" element is automatically captured by the plugin.

Use the submitHandler callback function to do stuff when the form is valid. As per docs, this is the proper place to do your ajax(). Without using the submitHandler, the form is submitted as a regular form and the page would redirect or reload. Using the submitHandler as outlined below will prevent all that.

$(document).ready(function () {  // DOM ready

    $("#myForm").validate({  // initialize the plugin
        submitHandler: function(form) {  // fires on valid form
            alert('yes valid');
            //$.post(...post my data using ajax..)
            alert('data posted successfully.');
            //clear form to submit another data
            clearForm();  // <- I don't see this function in your OP
            return false;
        }
    });  

});   

In your case, since you have a type="button", you need to manually capture the click and then trigger a submit.

    $("#addCustomer").click(function () {  // capture click

        $("#myForm").submit(); // trigger validation test & submit
        ....

Otherwise, you should eliminate this click handler entirely by changing your button into a type="submit".

<input type="submit" ...

OR

<button type="submit" ...

Working DEMO: http://jsfiddle.net/526Yc/


EDIT:

The unobtrusive-validation.js plugin included with ASP constructs and calls the .validate() method automatically. Since the jQuery Validate plugin will ignore all calls to .validate() after it's called once, you cannot call the .validate() method while also using the unobtrusive-validation.js plugin. And since the OP wanted to have more control over jQuery Validation, he opted to remove the unobtrusive-validation plugin and construct the call to the .validate() method himself.