jQuery验证有效,但如果条目不正确,仍然可以提交表单

时间:2016-05-20 09:42:10

标签: javascript php jquery forms

我在我的联系表单中使用了jquery验证插件,如果表单中出现错误则会返回,但即使条目不正确(例如名称不超过1个字符)我也可以提交表单发送包含错误数据的电子邮件。在条目完全正确之前,我怎么能阻止按钮激活?

$(document).ready(function() {
    var newHTML = '<div class="col-sm-12 text-center" style="color:white; background-color:#6f8595; padding-bottom:15px; border-radius:5px;"><h3>Thank you for your message!<br />We will get back to you as soon as possible!</h3></div>';

    $('#myform').validate();

    $('.btn').click(function(){
        var data = $("#myform").serialize();
        $('.form').html('').append(newHTML);
        $.post( "includes/sendmail.php", {data});
    });
});

2 个答案:

答案 0 :(得分:2)

像这样:

--no-bin-links

或者根据documentation,您可以在验证提交处理程序中执行AJAX调用 - 如下所示:

$(function() {
  var newHTML = '<div class="col-sm-12 text-center" style="color:white; background-color:#6f8595; padding-bottom:15px; border-radius:5px;"><h3>Thank you for your message!<br />We will get back to you as soon as possible!</h3></div>';
  $('#myform').validate();
  $('#myform').on("submit",function(e){
    e.preventDefault();
    if ($(this).valid()) {
      var data = $(this).serialize();
      $(this).html(newHTML);
      $.post( "includes/sendmail.php", {data});
    }
  }); 
});

答案 1 :(得分:0)

尝试使用此代码来解决问题:

$(document).ready(function() {

  var newHTML = '<div class="col-sm-12 text-center" style="color:white; background-color:#6f8595; padding-bottom:15px; border-radius:5px;"><h3>Thank you for your message!<br />We will get back to you as soon as possible!</h3></div>';

  $('#myform').validate({
    onSuccess: function(form) {
      var data = $(form).serialize();
      $.post( "includes/sendmail.php", {data});
      $(form).html(newHTML);
      return false;
    }
  });
});