无法使我的验证功能正常工作

时间:2014-05-01 21:14:34

标签: javascript html

我有这两个函数来计算他们以MM / DD / YYYY形式输入日期后的年龄。当它到达部分if(age<21)并且年龄不足时,它将通过我的消息提醒用户但不会返回false。我只是想不起它一直在努力。谢谢你的帮助!

function validateAge()
{
    var x = /^\s*/;
    var datemsg = "";

    var inputDate = document.code.myDate.value;
    inputDate = inputDate.replace(x, "");
    document.code.myDate.value = inputDate;

    getAge(new Date(inputDate));

    return true;

}

function getAge(birth)
{

    var today = new Date();
    var nowyear = today.getFullYear();
    var nowmonth = today.getMonth();
    var nowday = today.getDate();

    var birthyear = birth.getFullYear();
    var birthmonth = birth.getMonth();
    var birthday = birth.getDate();

    var age = nowyear - birthyear;
    var age_month = nowmonth - birthmonth;
    var age_day = nowday - birthday;

    if(age_month < 0 || (age_month == 0 && age_day <0)) 
    {
            age = parseInt(age) -1;
     }
    //alert(age);

    if(age < 21)
    {
    alert("You are not of drinking age");
    return false;
    }


}

3 个答案:

答案 0 :(得分:1)

如果您在validateAge功能更改时应该正确看到提醒

getAge(new Date(inputDate));

return true;

return getAge(new Date(inputDate));

您还需要添加

return true;

getAge()函数的末尾,以便它始终返回一个值。

答案 1 :(得分:0)

您没有在validateAge函数中返回getAge的结果,即validateAge始终返回true。您需要在validateAge中使用getAge的返回值执行某些操作,例如

function validateAge()
{
    var x = /^\s*/;
    var datemsg = "";

    var inputDate = document.code.myDate.value;
    inputDate = inputDate.replace(x, "");
    document.code.myDate.value = inputDate;    

    return getAge(new Date(inputDate));    
}

function getAge(birth)
{
    var today = new Date();
    var nowyear = today.getFullYear();
    var nowmonth = today.getMonth();
    var nowday = today.getDate();

    var birthyear = birth.getFullYear();
    var birthmonth = birth.getMonth();
    var birthday = birth.getDate();

    var age = nowyear - birthyear;
    var age_month = nowmonth - birthmonth;
    var age_day = nowday - birthday;

    if(age_month < 0 || (age_month == 0 && age_day <0)) 
    {
        age = parseInt(age) -1;
    }
    //alert(age);

    if(age < 21)
    {
        alert("You are not of drinking age");
        return false;
    }
    else
    {
        return true;
    }
}

答案 2 :(得分:0)

在你的函数validateage中,你正在调用函数getAge,但是根据它返回的值没有做任何事情。我相信,您假设如果getAge返回false,则validateage函数应该结束。相反,函数只是执行,然后只是忽略返回值,然后转到下一行并返回true。尝试:

if (!getAge(new Date(inputDate))) {
return false;
} else {
return true;
}