Gerry
Gerry

Reputation: 886

how do I prevent bootstrap modal close after jquery validation on a form?

Platform: ASP.NET 4.5, MVC 5, latest jQuery, bootstrap and jQuery validate

My issue is that once I validate the form I'd like to make an ajax call and not close the modal.

Here's my form:

<form id="loginform" action="">
    <div id="login-login">
          <span>
            <input type="email" name="login-email" id="login-email" placeholder="[email protected]" />
            <input class="btn btn-success submit" type="submit" id="login-submit" value="Submit" />
          </span>
    </div>
 </form>

My jQuery inside my document.ready

$("#login-form").popover(); // this is the overall modal id name

$("#loginform").validate({
    rules: {
        email: {
            required: true,
            email: true
        },
        submitHandler: function (form) {
            console.log("submit on ok");
            return false;
        }
    },
});

what happens:

When I enter an invalid email, I see the default jQuery validate fire and show me a friendly message. However, when the entry is correct, I don't see the console.log message (I also used an alert), the modal just closes and I don't want it to. No idea what else I'm supposed to do?

Any help appreciated.

Upvotes: 0

Views: 2041

Answers (1)

Sparky
Sparky

Reputation: 98718

<input type="email" name="login-email" id="login-email" placeholder="[email protected]" />

The jQuery Validation plugin is not working properly in your case because...

  1. Your element contains name="login-email" while you're targeting name="email". This must match the name attribute.

    rules: {
        "login-email": {  // <- this must match the 'name' of the field
            required: true,
            email: true
        },
        ....
    
  2. You've incorrectly nested the submitHandler within the rules option. This callback is a sibling of rules, not a child.

    rules: {
        ....
    },
    submitHandler: function (form) {
        console.log("submit on ok");  // this now fires on a valid form submit
        // ajax goes here
        return false;
    }
    

Working DEMO: http://jsfiddle.net/2axtuqed/

Upvotes: 3

Related Questions