我一直在寻找一种明确的方法来验证出生日期,当它分为三个不同的文本字段时。到目前为止,我有一个可以正确处理该问题的输入字段,但我无法更改 html 代码。所以我仍然需要它来符合 3 个文本字段组。我使用一个验证值的隐藏输入字段来读取该内容在三个字段中输入出生日期可以是一个解决方案。谁能帮我解决这个问题吗?
这是我的jsfiddle:http://jsfiddle.net/b8fubr5u/1/
$(document).ready(function () {
$.validator.addMethod("dob", function (value, element) {
var result = true;
var ageMin = 18;
var ageMax = 85;
//is the date valid?
//is it within the allowed range
var myDate = value.split("/");
var subDay = myDate[0];
var subMonth = myDate[1] - 1;
var subYear = myDate[2];
var subDate = new Date(subYear, subMonth, subDay);
// this will "correct" any out of range input
var calcDay = subDate.getDate();
var calcMonth = subDate.getMonth();
var calcYear = subDate.getFullYear();
// this checks to see if any of the submitted input was out of range
// comment this out to ignore the discrepancy if you want to set a "corrected" value below
if (calcDay != subDay || calcMonth != subMonth || calcYear != subYear) {
$.validator.messages.dob = "Invalid date";
result = false;
}
if (result) {
var currDate = new Date();
var currYear = currDate.getFullYear();
var currMonth = currDate.getMonth();
var currDay = currDate.getDate();
var age = currYear - subYear;
if (subMonth > currMonth) {
age = age - 1; // next birthday not yet reached
} else if (subMonth == currMonth && currDay < subDay) {
age = age - 1;
}
if (ageMin != undefined) {
if (age < ageMin) {
$.validator.messages.dob = "Min 18 years old";
result = false;
}
}
if (ageMax != undefined) {
if (age > ageMax) {
$.validator.messages.dob = "Invalid date";
result = false;
}
}
}
return result;
},
"Please enter a date in the format DD/MM/YYYY");
$("#form").validate({
rules: {
dateBirth: {
required: true,
dob: true
},
month: {
required: true,
dob: true
},
dobDay: {
required: true,
range: [1, 31]
},
dobMonth: {
required: true,
range: [1, 12]
},
dobYear: {
required: true
}
}
});
});
最佳答案
你可以使用这个:
$(".bday").on('keyup',function(){
var bday = $('[name="dobDay"]').val()+"/"+$('[name="dobMonth"]').val()+"/"+$('[name="dobYear"]').val();
$("#dateBirth").val(bday );
});
这是 fiddle 的工作:http://jsfiddle.net/b8fubr5u/8/
关于javascript - jquery验证多个文本字段中的出生日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28179827/