jQuery 验证插件 - 验证隐藏的输入而不可见?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7952181/
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-08-27 00:30:30  来源:igfitidea点击:

jQuery Validation plugin - Validating hidden inputs and not visible?

jqueryjquery-validate

提问by Gregor Menih

How would I validate hidden inputs and not visible text inputs with jQuery Form Validation plugin? The problem is, that I'm using auto-suggest plugin, which generates a hidden input for selected items:

我将如何使用 jQuery 表单验证插件验证隐藏的输入和不可见的文本输入?问题是,我正在使用自动建议插件,它为所选项目生成隐藏输入:

<input id="hiddenInput" type="hidden" name="something" value="1" />

I have 2 inputs like this (both of them only allow 1 item), which I want to validate and display the error in parent <td>. This is what I've gotten so far, but it doesn't display the error or submit a form, if the value is actually a number.

我有 2 个这样的输入(它们都只允许 1 个项目),我想验证并在 parent 中显示错误<td>。这是我到目前为止所得到的,但如果值实际上是一个数字,它不会显示错误或提交表单。

$("#form1").validate({
        rules: {
            something: {
                number:true,
                min:1,
                required:true
            }
        }
        })

回答by Josh

To allow validation of hidden elements, override the ignore and set it to empty string:

要允许验证隐藏元素,请覆盖 ignore 并将其设置为空字符串:

$("#form1").validate({
    ignore: "",
    rules: {
        something: {
            number:true,
            min:1,
            required:true
        }
    }
});

回答by Emre Erkan

You can use ignoreoption like this:

您可以使用这样的ignore选项:

$("#form1").validate({
    ignore: "input[type='text']:hidden",
    rules: {
        something: {
            number:true,
            min:1,
            required:true
        }
    }
});

Default value of ignoreoption is :hiddenwhich ignores all hidden fields and non-visible fields (display: noneetc.)

ignore选项的默认值是:hidden忽略所有隐藏字段和不可见字段(display: none等)

回答by CMcClymont

If the other answers aren't working for you, try this instead. It removes all ignores for the form, so it would validate everything including hidden fields:

如果其他答案对您不起作用,请尝试使用此方法。它删除了表单的所有忽略,因此它将验证包括隐藏字段在内的所有内容:

$.data($('form')[0], 'validator').settings.ignore = "";

To restore the settings to ignore hidden fields, use something like this:

要恢复设置以忽略隐藏字段,请使用以下内容:

$.data($('form')[0], 'validator').settings.ignore = "input[type='text']:hidden";

You can also use the above code to read back the current value.

您也可以使用上面的代码来读回当前值。

回答by lopradi

Another way to validate hidden inputs is this:

验证隐藏输入的另一种方法是:

$("#form1").validate({
        ignore: "not:hidden",
        rules: {
            something: {
                number:true,
                min:1,
                required:true
            }
        }
});