在 运行 时间将 submitHandler 添加到 jQuery validate()

Add submitHandler to jQuery validate() at run time

我正在使用 jQuery mt-select 来管理从数千种可能性的列表中自动完成的选择。

表单初始化为文本输入,例如

<input type="text" class="form-control" id="location[]" data-mt-filter-control="" autocomplete="on" style="width: auto;">

然后随着选择的添加,隐藏的输入会像

一样附加
<input type="hidden" name="locationID[1]" value="1786" data-tag-id="1786">

我希望这些表单在 JavaScript 主文件中初始化 validate() 之后添加一个 jQuery validate submitHandler。这将检查以确保至少做出了一项必需的选择。

When selections exist (or not) I have verified $("input[name^='locationID']").length gives the expected values.但是 returns 有效的形式使我相信没有添加 submitHandler。

控制台中没有错误或警告,并且 validate() 的行为与预期的不同,其中 class required 应用于非隐藏字段。

那么为什么 submitHandler 没有触发?

在这个表格的页面上我有:

<script type="text/javascript">
$(document).ready(function(){   
    $( "form" ).validate({
      submitHandler: function(form) {
            if($("input[name^='locationID']").length > 0) {
                 //Form is valid
                 alert('form data valid');
                 form.submit();
            }
            else {
                 //Form is invalid
                 alert('form data invalid');
            }
        },
      errorPlacement: function(error, element){
            if(element.attr("name") == "locationID[]"){
                error.appendTo($('#errorbox'));
                console.log('saw error');
            }else{
                error.appendTo( element.parent().next() );
                console.log('other errors');
            }
        }
    });
});
</script>

在所有页面的主 JS 文件中,我像这样初始化 validate():

$("form").validate({
        ignore: [], // include hidden fields
        errorPlacement: function(error, element) { 
            if ( element.is(":radio") ) {
                error.appendTo ( '#' + element.attr('name') + '_multiError' ); // eg rad_22_multiError
            } else if ( element.is(":checkbox") ) {
               error.appendTo ( '#' + element.attr('name').replace(/[\[\]]+/g,'') + '_multiError' );
            } else {
                error.appendTo( element.parent() );
            }
        },
        rules: {
            antispam: { equalToParam: "events" }
        }                      
    });

两个初始化实例不会合并彼此的选项,第二个会覆盖第一个。

您可以做的是将选项分解为存储的对象变量,并根据 class 形式扩展它们(如果 class 存在。

类似于:

var validateOpts = {
    ignore: [],
    errorPlacement: function (error, element) {...},
    rules: {...}
}

var extraOpts ={
    submitHandler:function(){...} 
    errorPlacement: function(error, element){...}
}

var $form =$('form');
 /* see if we need to combine the options or not */
if($form.is('.specialFormClass') ){
   /* yup...needs extending */
   $.extend( validateOpts, extraOpts);
}
/* now init the validation */
$form.validate(validateOpts);