来自 DOB 的 JavaScript 年龄验证,用于下拉选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16850946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 06:13:22  来源:igfitidea点击:

JavaScript Age Validation from DOB for Drop Down Selection

javascriptvalidationdrop-down-menu

提问by Curley5959

I have seen many Age Validation from DOB codes but none can I seem to get to work with my code.

我已经看到许多来自 DOB 代码的年龄验证,但我似乎无法使用我的代码。

Basically, I am required for my TAFE course to create a form with First Name, Surname, Email address, Contact phone number, Date of Birth and Area of Interest (which is a drop down box with Childrens and Adults Books).

基本上,我的 TAFE 课程要求我创建一个包含名字、姓氏、电子邮件地址、联系电话号码、出生日期和感兴趣的领域(这是一个包含儿童和成人书籍的下拉框)的表格。

I am required to validate the Date of Birth as being in the correct format. I have successfully done this and it equates for 30 day months and Leap Years as well.

我需要验证出生日期的格式是否正确。我已经成功地做到了这一点,它等同于 30 天月和闰年。

The next part requires the Area of Interest Drop Down box to validate on submit that the Age of the Person is over 18. BUT. Only if the Area Of Interest chosen is Adults Books.

下一部分需要兴趣区域下拉框以在提交时验证此人的年龄已超过 18 岁。但是。只有选择所选择的兴趣领域是成年书籍。

Now, I could do something simple and make it so all ages on and above 1996 will be rejected, but I would rather create a validation that does this from the DOB that was input, as I think this is what is to be expected.

现在,我可以做一些简单的事情并使它成为 1996 年及以上所有年龄段的人都将被拒绝,但我宁愿创建一个验证,从输入的 DOB 执行此操作,因为我认为这是可以预期的。

The DOB is input in the form of DD/MM/YYYY.

DOB 以 DD/MM/YYYY 的形式输入。

This is what I have so far:

这是我到目前为止:

<script language="JavaScript" type="text/javascript">
function validateForm()
{
    *snipped firstname, surname, email validation*
    var dob = document.getElementById("dateofbirth").value;
    *snipped dob validation*
    var area = document.getElementById("areaofinterest").value;
    if (area == "")
    {
        alert("Please select an Area of Interest!");
        return false;
    }
    var now = new Date();
    var birthdate = dob.split("/");
    var born = new Date(dob[2], dob[0], dob[1] * 1 - 1);
    var age = Math.floor((now.getTime() - born.getTime()) / (365.25 * 24 * 60 * 60 * 1000));
    if (area == "adults" && age<18)
    {
        alert("You need to be 18 years of age and older for the Adults books!");
        return false;
    }
return true;
}
</script>

I am only a beginner in JavaScript so there is probably something very obviously wrong with this piece of code. But basically what is written is what I want to achieve.

我只是 JavaScript 的初学者,所以这段代码可能有很明显的错误。但基本上写的是我想要实现的。

See if the Date of Birth is over 18 if the Adults Books Area of Interest is chosen.

如果选择了成人书籍感兴趣的领域,请查看出生日期是否超过 18 岁。

The HTML can be seen below of what I have:

可以在下面看到我所拥有的 HTML:

<form method="post" name="form1" onsubmit="return validateForm()" action="">
    Fields marked with * are required to be filled out!
    <br />
    First Name*: 
    <input type="text" id="firstname" name="First Name" placeholder="e.g. John" />
    <br />
    Surname*:
    <input type="text" id="surname" name="Surname" placeholder="e.g. Smith" />
    <br />
    Email address*:
    <input type="text" id="emailaddress" name="Email Address" placeholder="e.g. [email protected]" />
    <br />
    Contact phone number:
    <input type="text" id="phonenumber" name="Contact Phone Number" placeholder="e.g. 0410 224 567" />
    <br />
    Date of Birth*:
    <input type="text" id="dateofbirth" name="Date of Birth" placeholder="DD/MM/YYYY" />
    <br />
    Area of Interest*:
    <select id="areaofinterest" name="Area Of Interest" />
    <option value="">Select interest</option>
    <option value="children">Books for children</option>
    <option value="adults">Books for adults</option>
    </select>
    <br />
    <input type="submit" value="Submit" /><input type="reset" value="Reset" />
</form>

I appreciate any feedback. And I am sorry if this has been answered already. I know it has but I cant seem to get it to work for my purpose. I may made a simple format mistake or forgotten something out. It is probably something very obvious.

我感谢任何反馈。如果这已经得到回答,我很抱歉。我知道它有,但我似乎无法让它为我的目的工作。我可能犯了一个简单的格式错误或忘记了一些东西。这可能是非常明显的事情。

回答by Fasil kk

Demo : http://jsfiddle.net/mkginfo/LXEHp/7/

演示:http: //jsfiddle.net/mkginfo/LXEHp/7/

Use this JavaScript. tested and working well. Note: Please check all your code with this code. You will find few bugs in your past code. I am suggesting 'console.log' and firebug to check values.

使用此 JavaScript。经过测试并且运行良好。注意:请使用此代码检查您的所有代码。您会在过去的代码中发现一些错误。我建议使用 'console.log' 和 firebug 来检查值。

  function validateForm()
    {
        //*snipped firstname, surname, email validation*
        var dob = document.getElementById("dateofbirth").value;
       // *snipped dob validation*
        var area = document.getElementById("areaofinterest").value;
        if (area == "")
        {
            alert("Please select an Area of Interest!");
            return false;
        }

        var now = new Date();
        var birthdate = dob.split("/");
        var born = new Date(birthdate[2], birthdate[0]-1, birthdate[1]);
        age=get_age(born,now);
        if (area == "adults" && age<18)
        {
            alert("You need to be 18 years of age and older for the Adults books!");
            return false;
        }

    }

    function get_age(born, now) {
      var birthday = new Date(now.getFullYear(), born.getMonth(), born.getDate());
      if (now >= birthday) 
        return now.getFullYear() - born.getFullYear();
      else
        return now.getFullYear() - born.getFullYear() - 1;
    }

回答by ManKum

I just find a small bug in your age which returns as NaN.

我只是在你的年龄发现了一个小错误,它返回为NaN

Try to replace the bornvariable as follows:

尝试按如下方式替换出生变量:

    var born = new Date(dob.toString());

Note: Issue was with Date parsing! Hope this help! If not, let me know.

注意:问题在于日期解析!希望这有帮助!如果没有,请告诉我。

回答by jakber

Rather than subtracting the average number of milliseconds per year, try to figure out if the person has had his/her birthday this year (this depends on the timezone). Then subtract year of birth from current year and subtract 1 if the person has not had a birthday this year to get the age. Something like:

与其减去每年的平均毫秒数,不如试着弄清楚这个人今年是否过了他/她的生日(这取决于时区)。然后从当前年份中减去出生年份,如果此人今年没有过生日,则减去 1 以获得年龄。就像是:

function age(born, now) {
  var birthday = new Date(now.getFullYear(), born.getMonth(), born.getDate());
  if (now >= birthday) 
    return now.getFullYear() - born.getFullYear();
  else
    return now.getFullYear() - born.getFullYear() - 1;
}

回答by Kumod Singh

U can calculate exact age validation by this code. 
<head runat="server">
    <title>Untitled Page</title>

    <script type="text/javascript">
        function AgeValidation(ageOfCustomer)
        {
            var date=saildates.split('/')[2];
            var d = new Date();
            var lipday=((d.getFullYear()-date)/4);
            var month = d.getMonth()+1;
            var day = d.getDate();
            var output = day + '/' + month + '/' + d.getFullYear();
            var age=((daydiff(parseDate(output), parseDate(saildates))-lipday)/365);
            if(age > 18.000 || age== 18.000)
            {
                return true;
            }
            else
            {
                alert('Your age should be 18 or greater than 18 yrs!!!');
            }
        }
        function parseDate(str)
        {
            var mdy = str.split('/')
            return new Date(mdy[2], mdy[1]-1, mdy[0]);
        }
        function daydiff(first, second) 
        {
            return (first-second)/(1000*60*60*24)
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server"     OnClientClick="AgeValidation(this.form.TextBox1.value);"
            Text="Button" onclick="Button1_Click" />
    </div>
    </form>
</body>