我正在寻找使用jquery.validate.js创建自定义规则,该规则仅允许有效日期,例如2月为31天,30天和28天的月份(29为闰年)。您是否可以在不使用任何其他插件(如date.js)的情况下向我提供有关如何创建此自定义规则的建议?
我在下面添加了我当前的代码,并提供了一个指向我的jsFiddle示例的链接:
代码现已修复:
(function ($) {
// CUSTOM RULE METHOD TO CHECK FOR A VALID DATE
$.validator.addMethod('validateDate', function (value, element) {
if ($('#dob-day').val() != '0' && $('#dob-month').val() != '0') {
var date = $('#dob-year').val() + '-' + $('#dob-month').val() + '-' + $('#dob-day').val();
var day = $('#dob-day').val();
var month = $('#dob-month').val();
var year = $('#dob-year').val();
var tempDate = new Date(month + '/' + day + '/' + year);
if (day == '29' && month == '02') {
if (!(year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0))) {
day = '0';
}
} else {
if (!(month == (tempDate.getMonth() + 1)) || !(day == tempDate.getDate()) || !(year == tempDate.getFullYear())) {
day = '0';
}
}
if (day === '0' || month === '0' || year === '0') {
$('#dateCheck').val('');
} else {
$('#dateCheck').val('1');
return true;
}
}
});
$('#form').validate({
groups: {
dobGroup: 'BIRTH_DAY BIRTH_MONTH BIRTH_YEAR'
},
errorPlacement: function (error, element) {
if (element.attr('name') == 'BIRTH_DAY' || element.attr('name') == 'BIRTH_MONTH' || element.attr('name') == 'BIRTH_YEAR') {
error.insertAfter('#dob-year');
} else {
error.insertAfter(element);
}
},
rules: {
BIRTH_DAY: 'required',
BIRTH_MONTH: 'required',
BIRTH_YEAR: {
required: true,
validateDate: true
}
},
messages: {
BIRTH_DAY: 'Please enter a valid date of birth',
BIRTH_MONTH: 'Please enter a valid date of birth',
BIRTH_YEAR: 'Please enter a valid date of birth'
}
});
})(jQuery的);