jQuery .validate()的submitHandler未触发

17
我使用 Bootbox.js 动态创建了一个带表单的对话框,并使用 jQuery validate 插件验证用户输入。虽然验证成功,但当表单被填写正确时,submitHandler 被忽略了。出了什么问题?
submitHandler: function(form) {
    alert("Submitted!");
    var $form = $(form);
    $form.submit();
}

请看下面的完整示例。我看过其他帖子,在那里提出了类似的问题。不幸的是,它们似乎把表单呈现在页面上,而我是通过jQuery进行呈现。

$(document).on("click", "[data-toggle=\"contactAdmin\"]", function() {
  bootbox.dialog({
    title: "Contact admin",
    buttons: {
      close: {
        label: 'Close',
        className: "btn btn-sm btn-danger",
        callback: function() {}
      },
      success: {
        label: "Submit",
        className: "btn btn-sm btn-primary",
        callback: function() {
          $("#webteamContactForm").validate({
            rules: {
              requestType: {
                required: true
              }
            },
            messages: {
              requestType: {
                required: "Please specify what your request is for",
              }
            },
            highlight: function(a) {
              $(a).closest(".form-group").addClass("has-error");
            },
            unhighlight: function(a) {
              $(a).closest(".form-group").removeClass("has-error");
            },
            errorElement: "span",
            errorClass: "help-blocks",
            errorPlacement: function(error, element) {
              if (element.is(":radio")) {
                error.appendTo(element.parents('.requestTypeGroup'));
              } else { // This is the default behavior 
                error.insertAfter(element);
              }
            },
            submitHandler: function(form) {
              alert("Submitted!");
              var $form = $(form);
              $form.submit();
            }
          }).form();
          return false;
        }
      }
    },
    message: '<div class="row">  ' +
      '<div class="col-md-12"> ' +
      '<form id="webteamContactForm" class="form-horizontal" method="post"> ' +
      '<p>Please get in touch if you wish to delete this content</p>' +
      '<div class="form-group"> ' +
      '<div class="col-md-12"> ' +
      '<textarea id="message" name="message" class="form-control input-md" rows="3" cols="50">This email is to notify you the creator is putting a request for the following item\n\n' +
      this.attributes.getNamedItem("data-url").value + '\n\n' + '</textarea> ' +
      '<span class="help-block">Feel free to change the message and add more information. Please ensure you always provide the link.</span> </div> ' +
      '</div> ' +
      '<div class="form-group requestTypeGroup"> ' +
      '<label class="col-md-4 control-label" for="requestType">This request is for:</label> ' +
      '<div class="col-md-4"> <div class="radio"> <label for="Edit"> ' +
      '<input type="radio" name="requestType" id="requestType-0" value="Edit"> ' +
      'Editing </label> ' +
      '</div><div class="radio"> <label for="Delete"> ' +
      '<input type="radio" name="requestType" id="requestType-1" value="Delete"> Deletion</label> ' +
      '</div> ' +
      '</div> </div>' +
      '</form> </div>  </div>'
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.js"></script>

<a data-toggle="contactAdmin" data-title="help" data-url="http:/www.mydomain.com/some-url" href="#">Contact Web team</a>

在 jsFiddle 上查看

4个回答

26

检查jsFiddle的DOM,发现两个问题。

  1. "提交"按钮的<button>类型是type="button"

  2. "提交"按钮在<form></form>容器之外。

如果你想让jQuery验证插件自动捕获"提交"按钮的click事件...

  • 按钮必须是type="submit"
  • 按钮必须在<form></form>容器内部。

如果想要插件按预期工作,这两个条件必须满足。


你还错误地将.validate()方法放在模态对话框"提交"按钮的success回调函数中。

.validate()方法仅用于初始化该插件,并且应在创建表单后调用一次


编辑:

尝试操作后,发现Bootbox模态框插件可能存在一些严重的限制,会干扰表单的提交。

  1. 我在打开对话框后才初始化验证插件。

  2. 我在"提交"中使用.valid()方法来触发验证测试。

我可以成功初始化并使验证按预期工作,但对话框在实际表单提交之前被关闭了。也许有解决办法,但是经过查看Bootbox的文档后,并不明显。

https://jsfiddle.net/vyaw3ucd/2/


编辑2:

根据OP(原帖作者)的解决方案...

bootbox.dialog({
    // other options,
    buttons: {
        success: {
            label: "Submit",
            className: "btn btn-sm btn-primary",
            callback: function () {
                if ($("#webteamContactForm").valid()) {
                    var form = $("#webteamContactForm");
                    form.submit();  // form submits and dialog closes
                } else {
                    return false;  // keeps dialog open
                }
            }
        }
    }
});

然而,仅通过直接使用提供的form参数,您在使用jQuery Validate插件的submitHandler选项时不会出现任何错误。

submitHandler: function (form) {
    console.log("Submitted!");
    form.submit();
}

演示: https://jsfiddle.net/vyaw3ucd/5/


2

感谢Sparky的帮助,您提供的解决方案为我提供了答案。似乎submitHandler会对提交逻辑造成一些混淆。

我删除了submitHandler,并将以下内容添加到成功回调中,一切都按预期工作。

success: {
         label: "Submit",
         className: "btn btn-sm btn-primary",
         callback: function () {
             if($("#webteamContactForm").valid()){
                    var form = $("#webteamContactForm");
                    form.submit();
                } else {
                    return false;
                }
         }
    }

1
您不能真正删除submitHandler,因为它是插件内置的。但是,当使用自定义的submitHandler时,将form参数直接附加到submit()上将避免无限循环错误。请参见:https://jsfiddle.net/vyaw3ucd/5/ - Sparky
这是真的,如果没有附加表单参数,它将进入无限循环。然而,不添加submitHandler似乎相当于在代码中有它,就像你的例子一样。我已经在我的环境中测试过了,它按预期工作,只提交一次表单。再次感谢。 - david-l
是的。我的演示基本上只是内置的默认设置...这就是我的观点。 - Sparky

1

我知道这是一篇旧文章,但我想分享解决类似问题的方法。我无法通过按下回车键提交表单,但我可以在按下回车键时验证表单。因此,我使用了链式方法,现在我可以通过按下回车键提交表单。

jQuery:

  //Variables created without the keyword var, are always global, even if they are created inside a function.
    var form = $('#<?echo $PAGEID?>');
    var FormError = $('.alert-danger',form);
    var success = $('.alert-success',form);

     form.keypress(function(e){
         if(e.which == 13){ //TRIGGER SUBMIT THROUGH ENTER      
             document.getElementById('defaultActionButton').click(); 
         }
     }).validate({
        focusInvalid: false, // do not focus the last invalid input
        onkeyup: false, 
        ignore: ".ignore", //required for hidden input validation ie: hiddenRecaptcha
        rules:{
            "TYPE": {
                required: true,     
            },
            "MSG": {
                required: true,
                rangelength:[40,1000]
            },
            "CONTACT": {
                 required: {
                     depends: "#newuser:checked"
                 }
            },
            "EMAIL": {
                 required: true,
                 email: {
                    depends: function() {
                        if(!$("#newuser:checked"))
                            return true;
                        else
                            return false;
                    }
                 },
                 HTH_TelephoneEmail: {
                        depends: function() {
                            if($("#newuser:checked"))
                                return true;
                            else
                                return false;
                        }
                     }
            },          
            hiddenRecaptcha: {
                required: function () {
                    if (grecaptcha.getResponse() == '') {
                        return true;
                    } else {
                        return false;
                    }
                }
            }
        },
        messages: { // custom messages for form validation input
               "TYPE": {
                    required: 'Please select an option as it pertains to your inquiry'
               },
               "MSG": {
                    required: 'Please provide some content as it pertains to your inquiry'       
               },
               "CONTACT": {
                required: "Please enter a contact person or company"
               },
              hiddenRecaptcha: {
                required: function() {
                    $(".g-recaptcha:first").tooltip("enable").tooltip("show");
                }
              }
        },
        showErrors: function(errorMap, errorList) {
            // Clean up any tooltips for valid elements
            $.each(this.validElements(), function (index, element) {
                element = $(element);
                NoError_ToolTip(element);
            });
            // Create new tooltips for invalid elements
            $.each(errorList, function (index, error) {
                element = $(error.element);
                message = error.message;
                Error_ToolTip(element,message);
            });
        },                  
        invalidHandler: function (event, validator) { //display error alert on form submit     
            success.hide();
            $(document).scrollTop( $(".form-body").offset().top ); 
        },
         submitHandler: function () { 
       Submit_Complete(); //fires ajax call
   }
    });

1
你应该更改提交按钮的名称,因为存在命名冲突。例如,尝试将其从name="submit"更改为name="other"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接