1

我创建了一个包含以下内容的 javascript 文件:

(function ($) {
  //Define a Drupal behaviour with a custom name
  Drupal.behaviors.jarrowDynamicTextfieldValidator = {
    attach: function (context) {
        //Add an eventlistener to the document reacting on the
        //'clientsideValidationAddCustomRules' event.
        $(document).bind('clientsideValidationAddCustomRules', function(event){
            //Add your custom method with the 'addMethod' function of jQuery.validator
            //http://docs.jquery.com/Plugins/Validation/Validator/addMethod#namemethodmessage
            jQuery.validator.addMethod("typeValidator", function(value, element, param) {

             ...bunch of code here...

           }, jQuery.format('Field can not be empty'));
        });
      }
   };
})(jQuery);

我想做的是向选择框添加一个更改侦听器,以便在选择更改时调用此验证函数。我不确定我是否可以这样做,因为验证代码隐藏在几个函数中。这可能吗?

4

2 回答 2

1

通常,如果不稍微修改代码,您将无法调用该匿名函数,但这似乎是为 jQuery Validation Plugin 注册自定义验证规则的方式,一旦注册,您绝对可以通过插件使用该自定义规则API。

例如,以下代码添加了一个自定义规则:

jQuery.validator.addMethod("typeValidator", function(value, element, param) {

 ...bunch of code here...

}, jQuery.format('Field can not be empty'));

现在您可以在表单上初始化插件并调用该valid函数来验证表单。

$('#someForm').validate({
    rules: {
        someField: {
            typeValidator: true //use the custom validation rule
        }
    } 
});

现在您可以使用 . 检查表单是否有效$('#someForm').valid()

查看插件的 API以获取更多信息。

于 2013-08-16T23:17:17.063 回答
1

您的原始代码显示它的方式,不,您将无法调用任何这些函数,因为它们现在anonymous并且在父函数的范围内。

如果您要在调用它的函数之外为函数声明一个变量,那么您将能够重用该函数,因为它将在另一个函数的范围内是全局的。注意:如果您希望变量完全是全局的,或者更确切地说,无论您在代码中的哪个位置都可以访问它,只是不要var在变量前面写上,那么它将是“全局的”,即实际上相当于将变量放在window命名空间中。

这是使用您的代码的示例:

(function ($) {

    var customCallback = function(event){
        //Add your custom method with the 'addMethod' function of jQuery.validator
        //http://docs.jquery.com/Plugins/Validation/Validator/addMethod#namemethodmessage
        jQuery.validator.addMethod("typeValidator", function(value, element, param) {

         ...bunch of code here...

       }, jQuery.format('Field can not be empty'));
    };

   //Define a Drupal behaviour with a custom name
   Drupal.behaviors.jarrowDynamicTextfieldValidator = {
      attach: function (context) {
         //Add an eventlistener to the document reacting on the
         //'clientsideValidationAddCustomRules' event.
         $(document).bind('clientsideValidationAddCustomRules', customCallback);
      }
   };

   //now you can use that function again...
   $('#something').on('someEvent', customCallback );

})(jQuery);

请注意,您必须对该函数进行一些调整,以确保您的所有变量都可用,以及由于变量范围而出现的类似情况。因此,这可能需要进行一些调整以使其适用于您的场景。

于 2013-08-16T22:58:06.827 回答