var validator = $("#fullRegForm").validate({
errorLabelContainer: "#error_container",
wrapper: "li",
errorClass: "reg_error",
rules: {
fr_birthdate: {
date: true,
required: true,
minimumAge: true
},
fr_consent: {
required: function(element) {
var age = getAge($("#fr_birthdate").val());
if(age >=13 && age < 18){
$("#reg_consent").show();
} else {
$("#reg_consent").hide();
}
}
}
},
messages: {
fr_birthdate: {
date: "Please enter a valid date of birth",
required: "Please enter date of birth",
minimumAge: "under 13 years old are not allowed"
},
fr_consent: "13-17 years of age must have a parental consent"
}
我使用容器在表单中显示错误..但fr_consent消息的消息仍然显示年龄输入已超过18岁。我尝试使用相同的规则但不使用错误容器,它完美地工作。我错过了我的代码吗?
getAge:
function getAge(birthDate) {
var raw_date = birthDate;
var dobArr = raw_date.split("/");
var dob = new Date();
dob.setFullYear(dobArr[2], dobArr[0]-1, dobArr[1]);
var now = new Date();
function isLeap(year) {
return (((year % 4)==0) && ((year % 100)!=0) || ((year % 400)==0));
}
// days since the birthdate
var days = Math.floor((now.getTime() - dob.getTime())/1000/60/60/24);
var age = 0;
// iterate the years
for (var y = dob.getFullYear(); y <= now.getFullYear(); y++){
var daysInYear = isLeap(y) ? 366 : 365;
if (days >= daysInYear){
days -= daysInYear;
age++;
// increment the age only if there are available enough days for the year.
}
}
return age;
}
答案 0 :(得分:0)
尝试:
var age = getAge($("#fr_birthdate").val() * 1);
if(age < 18){
if(age >= 13){
$("#reg_consent").show();
}
}
答案 1 :(得分:0)
好的,感谢粘贴getAge代码,似乎工作正常。
required的函数可能需要返回一个布尔值。我认为Javascript默认返回false。所以目前你总是返回假
if(age >=13 && age < 18){
$("#reg_consent").show();
return false;
} else {
$("#reg_consent").hide();
return true;
}