Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I validate that someone is over 18 from their date of birth?

I am doing validation for Driver's Date of birth, it should be minimum of 18 from the current date.

var Dates = $get('<%=ui_txtDOB.ClientID %>');   
var Split = Dates.value.split("/");

if (parseInt(Split[2]) > 1993) 
{
    alert("DOB year should be less than 1993");
    Dates.focus();
    return false;
}  

I am using this above JavaScript validation for checking a person's DOB above 18, but it is not correct. I need to check with today's date and it should be above 18. How can I compare and check with the current date?

like image 665
Lakshmitha Avatar asked Aug 17 '11 10:08

Lakshmitha


People also ask

What is the correct way to check if a person is older than 18 years in JavaScript?

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.

What kind of validation can you do for date of birth?

1. Date format dd/MM/yyyy validation: The Date of Birth (DOB) will be first validated for dd/MM/yyyy format using Regular Expression (Regex). 2. 18+ Minimum Age validation: The difference between the age entered in the TextBox and the Current Date is minimum 18 years.


2 Answers

Try this.

var enteredValue = $get('<%=ui_txtDOB.ClientID %>');;
var enteredAge = getAge(enteredValue.value);
if( enteredAge > 18 ) {
    alert("DOB not valid");
    enteredValue.focus();
    return false;
}

Using this function.

function getAge(DOB) {
    var today = new Date();
    var birthDate = new Date(DOB);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }    
    return age;
}

Demo here: http://jsfiddle.net/codeandcloud/n33RJ/

like image 55
naveen Avatar answered Oct 27 '22 00:10

naveen


My approach is to find the date 18 (or any number) years ago from today, then see if that's after (greater) than their dob. By setting all values to date objects it makes the comparison easy.

function is_of_age(dob, age) {
  // dates are all converted to date objects
  var my_dob = new Date(dob);
  var today = new Date();
  var max_dob = new Date(today.getFullYear() - age, today.getMonth(), today.getDate());
  return max_dob.getTime() > my_dob.getTime();
}

Because the Date object can parse strings in a variety of formats, You don't have to worry too much about where dob is coming from. Simply call is_of_age("1980/12/4", 18); or is_of_age("2005-04-17", 13); or basically any string format or numeric that can be parsed as a Date parameter.

like image 29
unkerpaulie Avatar answered Oct 26 '22 23:10

unkerpaulie