Validate Date Of Birth And Set Age Limit In jQuery

calendar Using jQuery you are able to easily work out the age of a person by the date of birth. If you can work out the age you can add a age limit to stop under aged visitors from continuing into the link.

The following function will take an input of day, month and year. It will then take these values and create a new date object when compared to the current date we can work out the age of the visitor.

If there is a age limit and the visitors age is not more than the age limit we can then disallow entry.

$("#form").submit(function(){ 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; }); [/javascript]

Back to top

Learn how to code with Treehouse

  • Learn projects with access to 1000+ videos
  • Practice live with our Code Challenge Engine
  • Get help in our members-only forums

Start with a 7 day free trial