我有一个人年龄的下拉菜单,如果这个人的年龄低于 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");