Categories
PHP

Validating Age and Date of Birth

Dates of birth are commonly entered by users. Most dates require checks to see if the date is valid and also if it’s in a required range. In this tutorial, we’ll create a PHP script that validates the given date of birth to check whether it’s in a valid range.

  1. Demo: The working example.
  2. PHP date of birth verification script
  3. Validating date format
  4. Check the age limit by comparing dates
  5. Calculating your age

Check if the user is 18 years of age or older:

  1. In the <form>, the user is required to provide a date of birth.
  2. We validate this date of birth.
  3. We also validate this date if it’s within a range.

The range of valid dates in the example begins with the user being at least 18 years of age and ends with the user being at most 120 years of age.

If any date test fails, an error string is appended to the $message, and no further checks of the date are made. A valid date passes all the tests.

Try it, enter your date of birth


PHP Date of Birth Verification Script:

<?php
 $dob = $_POST['dob'] ?? ''; 
 $message = '';

 # Validate Date of Birth
 if (empty($dob)){
  # the user's date of birth cannot be a null string
  $message = 'Please submit your date of birth.';
 }
 elseif (!preg_match('~^([0-9]{2})/([0-9]{2})/([0-9]{4})$~', $dob, $parts)){
  # Check the format
  $message = 'The date of birth is not a valid date in the format MM/DD/YYYY';
 }
 elseif (!checkdate($parts[1],$parts[2],$parts[3])){
  $message = 'The date of birth is invalid. Please check that the month is between 1 and 12, and the day is valid for that month.';
 }
 
 if ($message == '') {
  # Convert date of birth to DateTime object
  $dob =  new DateTime($dob);

  $minInterval = DateInterval::createFromDateString('18 years');
  $maxInterval = DateInterval::createFromDateString('120 years');
 
  $minDobLimit = ( new DateTime() )->sub($minInterval);
  $maxDobLimit = ( new DateTime() )->sub($maxInterval);
 
  if ($dob <= $maxDobLimit)
   # Make sure that the user has a reasonable birth year
   $message = 'You must be alive to use this service.';
   # Check whether the user is 18 years old.
  elseif ($dob >= $minDobLimit) {
   $message = 'You must be 18 years of age to use this service.';
  }
 
  if ($message == '') {
   $today = new DateTime();
   $diff = $today->diff($dob);
   $message = $diff->format('You are %Y years, %m months and %d days old.');
  }
 }
?>
<p><b><?=$message?></b></p>
<form method="post" action="">
Your date of birth: <br>
<input type="text" name="dob" id="dob" placeholder="MM/DD/YYYY"><br>
<input type="submit" name="Submit" value="submit">
</form>

To understand how this script works, let’s break down the script into small chunks.

Validating date format

<?php
 # User sumibbted date via HTML form
 $dob = $_POST['dob'] ?? ''; 
 $message = '';

 # (1) Validate if the date entered or not
 if (empty($dob)){
  $message = 'Please submit your date of birth.';
 }

 # (2) Use regular expresstion to validate date format
 elseif (!preg_match('~^([0-9]{2})/([0-9]{2})/([0-9]{4})$~', $dob, $parts)){
  $message = 'The date of birth is not a valid date in the format MM/DD/YYYY';
 }

 # (3) Use checkdate to check if day, month and year are properly defined.
 elseif (!checkdate($parts[1],$parts[2],$parts[3])){
  $message = 'The date of birth is invalid. Please check that the month is between 1 and 12, and the day is valid for that month.';
 }

 if (empty ($message))
  echo "Valid DOB: $dob";
 else
  echo $message; 

1. The first check tests if a date has been entered.

2. The second check uses a regular expression to check whether the date consists of numbers and if it matches the template DD/MM/YYYY. Whatever the result of this check, the expression also returns the date into the array $parts:

  • the first grouped expression ([0-9{2}) is found in $parts[1],
  • the second grouped expression in $parts[2], and
  • the third grouped expression in $parts[3].
  • the preg_match( ) function stores the string matching the complete expression in $parts[0].

The overall result of processing a date that matches the template is that the day of the month is accessible as $parts[1], the month as $parts[2], and the year as $parts[3].

3. The third check uses the matched data stored in the array $parts and the function checkdate( ) to test if the date is a valid calendar date. For example, the date 31/02/1970 would fail this test.

Limiting age and comparing dates

<?php
 $dob =  new DateTime('12/12/2000');
 $upperLimit = new DateInterval('P18Y');
 $lowerLimit = new DateInterval('P120Y');
 $minDobLimit = ( new DateTime() )->sub($upperLimit);
 $maxDobLimit = ( new DateTime() )->sub($lowerLimit);

 if ($dob <= $maxDobLimit)
  echo 'Really! Are you still alive?';
 elseif ($dob >= $minDobLimit)
  echo 'You must be 18 years of age to use this service.';
 else
   echo 'Your age is between 18-120';
  1. First, we created the DateTime object for the given date of birth.
  2. Second, we created two DateInterval objects, the P18Y means 18-year and P120Y means 120-year.
  3. Third, we used the DateTime::sub method to retrieve the minimum and maximum date limits relative to the current date.
  4. Then we compared these DateTime objects ($dob, $minDobLimit, and $maxDobLimit) to determine whether the current date of birth is in the range of minimum age (18) and maximum age (120) limit.

Calculating your age

<?php
 $dob = new DateTime('12/12/2000');
 $today = new DateTime();
 $diff = $today->diff($dob);
 
 echo 'Today is: ';
 echo $today->format('m/d/Y').'<br>';
 echo $diff->format('You are %Y years, %m months and %d days old.');
 /* Prints something like this: 
 Today is: 09/18/2022
 You are 21 years, 9 months and 6 days old.
 */

We used the DateTime::Diff method which returns the difference between two DateTime objects. To understand the above example, you must understand the DateTime and DateInterval classes.


The Date and Time Tutorials: