我有一条规则,规定每个阶段的总数量必须等于预订的乘客数量。每个阶段都在DIV中定义,如下例所示: -
HTML
<div id="Stage_1">
<select data-stage="1" id="Quantity1" name="Items[1].Quantity">...</select>
<select data-stage="1" id="Quantity2" name="Items[2].Quantity">...</select>
<select data-stage="1" id="Quantity3" name="Items[3].Quantity">...</select>
</div>
<div id="Stage_2">
<select data-stage="2" id="Quantity4" name="Items[4].Quantity">...</select>
<select data-stage="2" id="Quantity5" name="Items[5].Quantity">...</select>
</div>
因此,例如,如果我在上述样本中预订了4名乘客,则数量1-3的总和值必须等于4,数量4-5的总和值也必须等于4.
然后我使用jQuery验证插件来验证...
脚本
function ValidateStages(value, element, options) {
var stage = options[0];
var valid = true;
var arrVS = new Array(0);
jQuery('div[id*="Stage_' + stage + '"] select[id*="Quantity"]').each(function () {
var e = jQuery(this);
if (arrVS[e.attr('data-stage')] == undefined) {
arrVS[e.attr('data-stage')] = 0;
}
arrVS[e.attr('data-stage')] += parseInt(e.val());
});
for (key in arrVS) {
if(arrVS[key] != MaxPassengers) {
valid = false;
}
}
return valid;
}
jQuery(document).ready(function () {
jQuery.validator.addMethod("validate_stages", ValidateStages, "Stage {0} error ");
jQuery('form:first').validate({
errorContainer: "#ValidationSummary",
errorLabelContainer: "#ValidationSummary",
rules: {
"Items[1].Quantity": { validate_stages: [1] } ,
"Items[2].Quantity": { validate_stages: [1] } ,
"Items[3].Quantity": { validate_stages: [1] } ,
"Items[4].Quantity": { validate_stages: [2] } ,
"Items[5].Quantity": { validate_stages: [2] }
},
});
});
问题
我有以下问题: -
页面上的每个下拉列表都会显示错误消息。因此,例如,如果说“阶段1错误阶段1错误阶段1错误阶段2错误阶段2错误”。如果阶段1和阶段2无效,则应显示“阶段1错误阶段2错误”
正如您所看到的那样,规则是硬编码的。我确实试图创建一个动态创建规则的函数(见下文),但我不知道如何应用它。如果我尝试执行规则:{GetRules()} 那么我只会收到一条错误说“预期:”
var GetRules = function () {
var rules = '';
jQuery('div[id*="Stage_"]').each(function (i) {
jQuery('#' + jQuery(this).attr('id') + ' select[id*="Quantity_"]').each(function (j) {
var name = jQuery(this).attr('name');
rules = rules + '"' + name + '": { validate_stages: [' + (i + 1) + '] }, ';
});
});
if (rules.length > 2) {
rules = rules.slice(0, -2);
}
return rules;
}
答案 0 :(得分:0)
自己想出来。我需要在验证器上对控件进行分组。完成此操作后,我能够在单独的容器中显示每个阶段的错误。组和规则是动态创建的,如下所示......
var validation =
{
errorContainer: "#ValidationSummary",
errorLabelContainer: "#ValidationSummary",
groups: {}, rules: {}, messages: {}
};
jQuery('div[id*="Stage_"]').each(function (i) {
jQuery('#' + jQuery(this).attr('id') + ' select[id*="Quantity_"]').each(function (j) {
var name = jQuery(this).attr('name');
var Rule = name;
validation.rules[Rule] = { validate_stages: [i + 1] };
});
});
jQuery('div[id*="Stage_"]').each(function (i) {
var group_ctrls = ''
jQuery('#' + jQuery(this).attr('id') + ' select[id*="Quantity_"]').each(function (j) {
var name = jQuery(this).attr('name');
group_ctrls = group_ctrls + name + ' ';
});
validation.groups['group_' + i] = group_ctrls;
});
jQuery('form:first').validate(validation);