Igor Simic
7 years ago

Javascript - 18 years validation

How to validate that user is 18 or older from date of birth? Based on the user birthday input we can calculate in JavaScript is this user 18 or older by using this function:

function underAgeValidate(birthday){
	// it will accept two types of format yyyy-mm-dd and yyyy/mm/dd
	var optimizedBirthday = birthday.replace(/-/g, "/");

	//set date based on birthday at 01:00:00 hours GMT+0100 (CET)
	var myBirthday = new Date(optimizedBirthday);

	// set current day on 01:00:00 hours GMT+0100 (CET)
	var currentDate = new Date().toJSON().slice(0,10)+' 01:00:00';

	// calculate age comparing current date and borthday
	var myAge = ~~((Date.now(currentDate) - myBirthday) / (31557600000));

	if(myAge < 18) {
     	    return false;
	    return true;



Notice that we are setting time for birthday date and current date to same hour timestamp 01:00:00  to have exactly precise comparison.