【问题标题】:jquery validation. custom rules using selector syntaxjQuery 验证。使用选择器语法的自定义规则
【发布时间】:2011-10-26 10:20:32
【问题描述】:

我正在编写一个使用 jQuery Validation 的系统,该系统通过 jSON 引入自定义规则、消息并在单个页面中动态验证多个表单。一切都在顺利进行,除了我找不到任何关于自定义规则正确语法的体面信息......

例如:

我知道这行得通....

"ui_txt_GCPostcode": {
    "required": "input[name=ui_rb_ItemAddress][value=Recipient]:checked"
}

我在这里是说,只有在选中名称为 ui_rb_ItemAddress 且值 Recipient 的列表中的单选按钮时才需要 ui_txt_GCPostcode

在我看来,我可以根据包含特定选择器属性的 dependency expressions 分配规则。

但是这不起作用.....

"ui_sel_PCSelect": {
        "required": "input[name=ui_txt_PostCodeSearch]:hidden, input[name=ui_txt_Address]:hidden"
    }

即使我有 ui_txt_Address 可见,验证器仍在触发。

我什至使用 ignore 隐藏属性设置验证器,例如。

                // Validate the form once the defaults are set.
                $validator = $form.validate({
                    // This prevents validation from running on every
                    // form submission by default.
                    onsubmit: false,
                    messages: messages,
                    rules: rules,
                    errorContainer: $container,
                    errorLabelContainer: $("ol", $container),
                    wrapper: "li",

                    // Ignore hidden items. Why is this not working??
                    ignore: ":hidden"
                });

有什么想法吗??我的截止日期很紧,我开始恐慌了。

【问题讨论】:

  • input[name=ui_txt_PostCodeSearch] input[name=ui_txt_Address] 被隐藏时,您是否希望ui_sel_PCSelect 成为required
  • @Andrew:是的......正是这样。我刚刚设法绕过它,但我希望有一个干净而强大的解决方案。

标签: jquery jquery-plugins jquery-validate


【解决方案1】:

这个选择器:

"input[name=ui_txt_PostCodeSearch]:hidden, input[name=ui_txt_Address]:hidden"

如果第一个第二部分为真(请参阅multiple selector),将触发required 规则。这就是即使规则可见也会触发的原因。

如果您想在 两者 都隐藏的情况下使元素成为必需元素,则可能必须提供依赖函数而不是表达式:

"ui_txt_GCPostcode": {
    "required": function() {
        return $("input[name='ui_rb_ItemAddress'][value='Recipient']:checked").length &&
            $("input[name='ui_rb_ItemAddress'][value='Recipient']:checked").length;
    }
}

至于ignore 属性不起作用,那是为了忽略匹配选择器的字段(所以:hidden 会告诉验证器不要验证隐藏字段)。不确定您是否以这种方式使用它。

【讨论】:

    猜你喜欢
    • 2011-02-07
    • 2018-03-02
    • 2011-04-10
    • 2017-09-12
    • 2016-04-10
    • 1970-01-01
    • 1970-01-01
    • 2019-12-01
    相关资源
    最近更新 更多