我在使用 jQuery 验证来验证动态生成的月份和日期输入时遇到了麻烦。基本上,我想确保某些月份不能超过 30 天,而 2 月不能超过 29 天。当月份和日期输入固定时,我的方法效果很好。我很感激任何建议。这是一个演示。
HTML
<form method="post" id="form1" action=index.html>
<table class="tab tab_Application" border="0">
<tr>
<th>
<label for="id_noa">Number of Applications:</label>
</th>
<td>
<select name="noa" id="id_noa">
<option value="">Make a selection</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</td>
</tr>
<tr id='noa_header' style="display:none">
<th>App#</th>
<th>Month</th>
<th>Day</th>
<th>Mass Applied (kg/hA)</th>
<th>Slow Release (1/day)</th>
</tr>
</table>
<tr>
<input type="submit" />
</tr>
</form>
JS
$(document).ready(function () {
$('#form1').validate({ // initialize the plugin
submitHandler: function (form) {
alert('valid form submitted');
return false;
},
rules: {
noa: "required"
}
});
var i = 1
$('#id_noa').change(function () {
var total = $(this).val()
$('#noa_header').show()
while (i <= total) {
$('.tab_Application').append('<tr class="tab_noa1"><td><input type="text" size="5" value="' + i + '"/></td><td><input type="text" size="5" name="mm' + i + '" id="id_mm' + i + '""/></td><td><input type="text" size="5" name="dd' + i + '" id="id_dd' + i + '""/></td><td><input type="text" size="5" name="ma' + i + '" id="id_ma' + i + '""/></td><td><input type="text" size="5" name="sr' + i + '" id="id_sr' + i + '" value="0""/></td></tr>');
i = i + 1;
}
while (i - 1 > total) {
$(".tab_Application tr:last").remove();
i = i - 1
}
$('</table>').appendTo('.tab_Application');
$('[name*="mm"]').each(function () {
$(this).rules('add', {
required: true,
monthCheck: true
});
});
$('[name*="dd"]').each(function () {
$(this).rules('add', {
required: true,
dayCheck: true
});
});
});
////define validation functions
$.validator.addMethod(
"monthCheck",
function (value) {
return mmCheck(value);
},
"Please enter a right month");
$.validator.addMethod(
"dayCheck",
function (value, element) {
return ddCheck(value, element);
},
"Please enter a right day");
function mmCheck(value) {
var mmValue = value;
if (mmValue < 1 || mmValue > 12) return false;
return true;
}
function ddCheck(value, element) {
var mmValue1 = $(element).closest("tr").find('input').val();
var ddValue1 = value;
if (ddValue1 < 1 || ddValue1 > 31) return false;
else if (mmValue1 === 2 && ddValue1 > 29) return false;
else if ((mmValue1 === 4 || mmValue === 6 || mmValue1 === 9 || mmValue1 === 11) && (ddValue1 > 30)) return false;
return true;
}
});