简体   繁体   English

jQuery验证自定义方法规则和带有动态名称的消息?

[英]jQuery validation custom method rule and message with dynamic name?

I have a validation rule that I want to add using a variable varFunctionID, which represents a custom validation method. 我有一个要使用变量varFunctionID添加的验证规则,该变量表示自定义验证方法。 Rather than looking for the value of the variable, it searches for a function called varFunctionID, which does not exist. 而不是查找变量的值,而是搜索一个不存在的名为varFunctionID的函数。 How can I ensure that the value, not the name, of the variable is used? 如何确保使用变量的值而不是名称? Also, I cannot use the name in place of the variable. 另外,我不能使用名称代替变量。

var varFunctionID = "nameOfMyCustomValidationFunction";

$('#myField').rules('add', {
    varFunctionID: true
    },
    messages: {
        varFunctionID: "My message."
    }
});

* EDIT * There is no way to make the name dynamic. *编辑*没有办法使名称动态。 The way to handle such a need is to pass in a parameter to the validation method, like so: 处理此类需求的方法是将参数传递给验证方法,如下所示:

$('#myField').rules('add', {
    myFunction: { myParm: "parm" }
    },
    messages: {
        myFunction: "My message."
    }
});

jQuery.validator.addMethod("myFunction", function (value, element, options) {
            var passParm= options.myParm;
});

Not sure why you would need to do such a thing. 不知道为什么您需要这样做。 As your OP is written, it's entirely unclear why you can't use the actual name of the custom method in the first place. 在编写OP时,目前还不清楚为什么不能首先使用自定义方法的实际名称。

You cannot do what you're asking . 你无法做到你的要求 You would need to use the actual name of your custom method within the .rules() method. 您需要在.rules()方法中使用自定义方法的实际名称。


EDIT : My previously suggested workaround is not viable. 编辑 :我以前建议的解决方法不可行。

The custom method is not meant to have a "dynamic" name and I'm not sure why the name would ever need to be dynamic. 自定义方法并不意味着要有一个“动态”名称,而且我不确定为什么该名称必须是动态的。 The custom method is created and you either assign it to one or more fields or don't. 自定义方法已创建,您可以将其分配给一个或多个字段,也可以不分配。 Anything "dynamic" about this function would be taken care of by passing in custom parameters. 通过传入自定义参数,可以解决有关此功能的任何“动态”问题。

See .addMethod() method documentation . 请参阅.addMethod()方法文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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