0

我有一个人年龄的下拉菜单,如果这个人的年龄低于 85 岁,我需要在我的“current_health”单选按钮上设置一个特定的值才能继续。我正在使用 jQuery 验证插件和表单向导插件,它允许我让用户一次浏览表单 2 个问题。用户填写这两个问题,然后单击“下一步”并检查验证。

我尝试了很多补救措施,这就是我目前拥有的:

var validator = $("#order-form").validate({
            errorContainer: container,
            errorLabelContainer: $("ul", container),
            wrapper: 'li',
            meta: "validate",
            rules: {
                current_health: {
                    equalTo: "#requiredUnder85",
                    required:{
                        depends: function(element){
                            return $("#age").val() < 85;
                        }
                    }
                }
            }
        });

“requiredUnder85”是一个隐藏字段,其文本等于需要检查验证才能通过的单选框的值。

如果年龄 < 85,current_health 需要匹配“Terminal/Chronic Illness”,否则 current_health 是什么无关紧要。这是我需要验证的。Age 是一个选择框,current_health 是一个单选按钮集。

我一直在四处寻找帮助,但我无法实现我所需要的。任何帮助表示赞赏

编辑:包括表单标记。(注意:如您所见,我也在使用 smarty)

<label for="age">What is your current age?</label><br/>        
<select id="age" name="age" {literal} class="input-required {validate:{required:true}}" title="Required"{/literal}>
    <option value=""></option>
    {include file='snippets/age.tpl'}
</select><br/><br/>

<label for="current_health">Choose the most applicable health status</label><br/>
<input type="radio" name="current_health" id="ch1" value="Healthy" {if $data.current_health eq 'Healthy' OR !isset($data.current_health)}checked="checked"{/if} />  Healthy<br/>
<input type="radio" name="current_health" id="ch2" value="Terminal/Chronic Illness" {if $data.current_health eq 'Terminal/Chronic Illness'}checked="checked"{/if}/> Terminal/Chronic Illness

编辑 2:添加自定义规则后,如果不满足条件,我将无法再在表单向导中前进,但我没有显示错误消息。

var validator = $("#order-form").validate({
    errorContainer: container,
    errorLabelContainer: $("ul", container),
    wrapper: 'li',
    meta: "validate",
    rules: {
        current_health: {
            ageAndHealth: true
        }
    }
});

jQuery.validator.addMethod("ageAndHealth", function(value, element, parameter) {
    if($('#age').val() < 85 && value != "Terminal/Chronic Illness"){
        return false;
    }
    return true;
}, "This is the error message");
4

1 回答 1

1

听起来您只需要为这种情况创建一个自定义方法/规则......

请参阅:http: //jqueryvalidation.org/jQuery.validator.addMethod/

jQuery.validator.addMethod("myRule", function(value, element, parameter) {
    // your function for evaluating the element's validity
    // return true when it passes
    // return false when it fails and message will automatically display
}, "This is the error message");

这些参数被传递到您的函数中:

value
类型:String
已验证元素的当前值

element
类型:
要验证的元素

参数
类型:为方法指定的字符串
参数,例如min:5,参数为5,范围:[1, 5]为[1, 5]


像任何其他规则一样定义它...

rules: {
    current_health: {
        myRule: true
        // myRule: 85 // alternatively, you could pass parameters to your function
    }
}
于 2013-08-30T17:57:42.323 回答