Validate Age

This snippet presupposed an HTML form with and ID of "age-form" and three inputs (text or select) with the IDs "day", "month", and "year" respectively.

	var day = $("#day").val();
	var month = $("#month").val();
	var year = $("#year").val();
	var age = 18;
	var mydate = new Date();
	mydate.setFullYear(year, month-1, day);

	var currdate = new Date();
	currdate.setFullYear(currdate.getFullYear() - age);
	if ((currdate - mydate) < 0){
		alert("Sorry, only persons over the age of " + age + " may enter this site");
		return false;
	return true;

You may wish to do something more elegant than an alert, and should also probably validate the form with server side code or else this protection only works for users with JavaScript enabled.


  1. User Avatar
    Permalink to comment#
  2. User Avatar
    Cary Hartline
    Permalink to comment#

    That’s nice, but I don’t see a point in age validation. Who, under the restricted age, gives their correct age.

    • User Avatar
      Permalink to comment#

      Becuase of the legal side of things. With the age validation in place, they cannot be sued by anybody as the person who has accessed the site has stated they are old enough and violated the terms of use.

  3. User Avatar
    Permalink to comment#

    point is, for example, law in country…

  4. User Avatar
    Permalink to comment#

    Thanks for this piece of code, it’s very helpful.

    I’ve been working with this and it seems to only get your age with an accuracy to year of birth. So, say I was turning 18 years old this year, but still only 17, it would still let me through.

    Is there a way to be more accurate to validate according to day and month as well?


    • User Avatar
      Permalink to comment#

      This will probably work for your requirements.

      if(currdate.getFullYear()-mydate.getFullYear()>=0 && currdate.getMonth()-mydate.getMonth()>=0 && currdate.getDate()-mydate.getDate()>=0)
      return true;
      return false;
  5. User Avatar
    Permalink to comment#

    mydate.setFullYear(year, month-1, day); why -1 for month ?

Leave a Comment

Posting Code!

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.