简体   繁体   中英

bootbox + jQuery.validator for AJAX login form not working

I have the following fiddle with my issue.

When I press Sign In on the modal empty form, the validator should mark the fields in error. Additionally, the form should submit when validation passed.

There are no errors in console and it does not work.

This line in my code below seems to not work like it does in this other fiddle :

var form = $("#ajax_login_form");
form.validate();

What did I miss? Thanks!

Using jQuery validator, I have the following JS:

/**
 * Login modal form
 */
function loginModal() {
  var content = $("#login_form").html();
  $("#login_form").detach();

  bootbox.dialog({
    title: "TEST",
    message: content,
    size: 'medium',
    className: 'modal-primary',
    buttons: {
      success: {
        label: "Sign in",
        className: "btn btn-sm btn-primary",
        callback: function() {
          loginValidator();
          var form = $("#ajax_login_form");
          form.validate();
          return false; // keeps dialog open
        }
      }
    },
    onEscape: function() {
      logout();
    }
  });
}

/**
 * Validator for login AJAX form
 */
function loginValidator() {
  $("#ajax_login_form").validate({
    rules: {
      email: {
        required: true,
        email: true
      },
      password: {
        required: true,
        minlength: 8
      }
    },
    messages: {
      email: "Please enter a valid email address",
      password: {
        required: "Please provide a password",
        minlength: $.validator.format("Your password must be at least {0} characters long")
      }
    },
    submitHandler: function(form) {
      alert("submitted!");
      return false;
    }
  });
}

The HTML is:

<div id="login_form" style="display:none;">

  <form method="post" action="#" accept-charset="UTF-8" class="form" id="ajax_login_form" name="ajax_login_form">

    <div class="form-group">
      <input class="form-control" id="email" placeholder="Your email" name="email" type="email" />
    </div>

    <div class="form-group">
      <input class="form-control" id="password" placeholder="Your password" name="password" type="password" value="" />
    </div>

    <div class="form-group">
      <input type="checkbox" name="remember" />
      <label for="remember">&nbsp;Remember Me
      </label>
    </div>
  </form>
</div>

Replace

form.validate();

with

form.valid();

This should work as expected (works for me).

Edit : replace with

form.submit();

if you want to submit the form if it's valid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM