Grow your CSS skills. Land your dream job.

Last updated on:

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.

$("#age-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;
});

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.

Comments

  1. 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.

    • Daniel
      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.

  2. butHa
    Permalink to comment#

    point is, for example, law in country…

  3. Paul
    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?

    Thanks

Leave a Comment

Posting Code

Markdown is supported in the comment area, so you can write inline code in backticks like `this` or multiline blocks of code in in triple backtick fences like ```this```. You don't need to escape code in backticks, Markdown does that for you.

Sadly, it's kind of broken. WordPress only accepts a subset of HTML in comments, which makes sense, because certainly some HTML can't be allowed, like <script> tags. But this stripping happens before the comment is processed by Markdown (via Jetpack). It seems to me that would be reversed, because after Markdown processes code in backticks, it's escaped, thus safe. If you think you can fix this issue, get in touch!

If you need to make sure the code (typically HTML) you post absolutely posts correctly, escape it and put it within <pre><code> tags.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".