I have a rule that says for each Stage the total quantity selected must equal the number of passengers on a booking. Each Stage is defined in a DIV like in this example:-
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>
So for example if I have a booking with 4 passengers in the above sample the sum value of Quantities 1-3 must equal 4 and also the sum value of the Quantities 4-5 must also equal 4.
I then use the jQuery validation plugin to validate…
Script
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] }
},
});
});
Questions
I have the following issues:-
-
The error message is displayed for each dropdown on the page. So for example if says “stage 1 error stage 1 error stage 1 error stage 2 error stage 2 error“. If Stage 1 and Stage 2 are invalid it should just display “stage 1 error stage 2 error“
-
As you can see the rules are hard coded. I did try to create a function (see below) that creates the rules on the fly but I don’t know how to apply it. If I try and do rules: { GetRules() } then I just get an error saying “expected :”
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; }
Figured it out myself. I needed to group the controls on the validator. Once this was done I was able to display each stages error in a separate container. The groups and rules are created dynamically as shown below…