javascript jQuery 在元数据标签和消息中使用多个参数验证自定义验证器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23001516/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 00:10:17  来源:igfitidea点击:

jQuery Validate custom validator with multiple params in metadata tag and message

javascriptjqueryjquery-validate

提问by Delorian

I want to use jQuery Validate to validate an age is between two years in a metadata tag, and specify the years as parameters.

我想使用 jQuery Validate 来验证元数据标签中的年龄介于两年之间,并将这些年指定为参数。

The problem I have is I can't pass the parameters as an object so I don't know how to access them in the error message (and can't find any documentation on it).

我遇到的问题是我无法将参数作为对象传递,所以我不知道如何在错误消息中访问它们(并且找不到任何关于它的文档)。

HTML

HTML

<input type="text" name="dob" id="dob" validAge="[17,66]" />


JavaScript


JavaScript

jQuery.validator.addMethod('validAge', function (value, element, params) {
        value = eLifeViewModel.age();
        if (value === '') {
            return false;
        }
        var range = JSON.parse(params);
        return value > range[0] && value < range[1];
    }, $.format('Applicants must be older than {0} and younger than {1} years of age'));


The output for {0} is my parameter string and {1} is the HTTPInputElement.


{0} 的输出是我的参数字符串,而 {1} 是 HTTPInputElement。


I've now written a minAge and maxAge function to get around this, but I'd still be keen to get a resolution to this.


我现在已经编写了一个 minAge 和 maxAge 函数来解决这个问题,但我仍然渴望得到一个解决方案。

采纳答案by Sparky

You can't find documentation, because you can't do it.

你找不到文档,因为你做不到。

Using the jQuery Validation plugin and a custom method, you cannot declare the validAgerule inline when you need to pass parameters.

使用 jQuery 验证插件和自定义方法,validAge当您需要传递参数时,您无法内联声明规则。

<input type="text" name="dob" id="dob" validAge="[17,66]" />

Only certain rules that can be declared with a boolean (can be declared as classnames), or rules that are also HTML5 validation attributes can be declared inline.

只有某些可以用布尔值声明的规则(可以声明为class名称),或者也是 HTML5 验证属性的规则可以声明为内联。

For your custom method with parameters, it must(can) be declared within the .validate()method...

对于带有参数的自定义方法,它必须可以)在.validate()方法中声明...

$('#myform').validate({
    // your options, rules, etc,
    rules: {
        dob: {
            validAge: [17,66]
        }
    }
});


EDIT:

编辑

As pointed out by @John Bubriski, this should be working. The OP was not accessing the parameters correctly in his custom method.

正如@John Bubriski 所指出的,这应该有效。OP 在他的自定义方法中没有正确访问参数。

The OP was using JSON.parse...

OP 使用的是 JSON.parse ...

var range = JSON.parse(params);

which gives a syntax error in the console since it's not recognizing paramsas a valid JSON string. Parsing the paramsvariable is not necessary.

这会在控制台中出现语法错误,因为它无法识别params为有效的 JSON 字符串。params不需要解析变量。

The parameters are passed into the function as params, so they can be accessed directly as params[0], params[1], etc.

参数被传递到功能params,因此它们可以被直接作为访问params[0]params[1]等等。

jQuery.validator.addMethod('validAge', function (value, element, params) {
    value = eLifeViewModel.age();
    if (value === '') {  // <- You do NOT need this! 
    /* Use the "required" rule instead of this conditional */
        return false;
    }
    return value > params[0] && value < params[1];
}, $.format('Applicants must be older than {0} and younger than {1} years of age'));

回答by John Bubriski

This does work, at least in the latest jQuery/Validate. Here is a fiddle showing some custom validators, 3 of which take an array of parameters: http://jsfiddle.net/jbubriski/YQgEq/120/

这确实有效,至少在最新的 jQuery/Validate 中是这样。这是一个显示一些自定义验证器的小提琴,其中 3 个接受一组参数:http: //jsfiddle.net/jbubriski/YQgEq/120/

Here is one of the examples that takes string params. Instead of saying data-rule-customname="true", you specify the parameters data-rule-customname='["string",1,2,3]'.

这是采用字符串参数的示例之一。与其说,不如data-rule-customname="true"指定参数data-rule-customname='["string",1,2,3]'

(Note the flipping of quotes... using single quotes to denote the strings doesn't seem to work. Use double quotes)

注意引号的翻转......使用单引号表示字符串似乎不起作用。使用双引号

Markup:

标记:

<div>
    Custom 3 (Requires 'pig' or 'mouse'): <input type="text" id="custom3" name="custom3" data-rule-required="true" data-rule-customv3='["pig","mouse"]' data-msg-customv3="Enter a cool animal name!" />
</div>

JS:

JS:

jQuery.validator.addMethod("customv3", function(value, element, params) {
    if (this.optional(element))
        return true;

    for (var i = 0; i < params.length; i++)
        if (value == params[i])
            return true

    return false;
}, jQuery.validator.format("Please enter one of the following values: {0} {1}"));

The only issue with the above example is that I'm not sure if there is a way to dynamically generate the error message if you're expecting nparameters. The current code works fine, but assumes 2 parameters.

上述示例的唯一问题是,如果您需要n参数,我不确定是否有办法动态生成错误消息。当前代码工作正常,但假设有 2 个参数。

I also have a blog post that details some other aspects of using attribute-based validation: http://johnnycode.com/2014/03/27/using-jquery-validate-plugin-html5-data-attribute-rules/

我还有一篇博文详细介绍了使用基于属性的验证的其他一些方面:http: //johnnycode.com/2014/03/27/using-jquery-validate-plugin-html5-data-attribute-rules/

回答by NMC

The paramsvariable doesn't return a string but an object.

params变量不返回字符串而是一个对象。

Try to pass the range directly from params :

尝试直接从 params 传递范围:

jQuery.validator.addMethod('validAge', function (value, element, params) {
        value = eLifeViewModel.age();
        if (value === '') {
            return false;
        }
        return value > params[0] && value < params[1];
    }, $.format('Applicants must be older than {0} and younger than {1} years of age'));