How to Validate Date of Birth and Calculate Age in PHP.
In a previous post, we discussed how to calculate age from a given date of birth in PHP. In this article, we’ll delve deeper into the process by focusing on how to validate the date of birth before calculating the age. We’ll also optimize the existing code and explore some additional ideas to enhance its functionality.
Validating Date of Birth
Before calculating age, it’s crucial to ensure that the provided date of birth is valid. Let’s optimize the validation process with a simple and efficient PHP function.
<?php
function validate_date_and_get_age($date){
$dateparameters = array();
$date = preg_replace("/[^0-9\']/", ",", $date);
$date = explode(',', $date);
$age = '';
if(count($date) == 3){
for ($i = 0; $i < 3; ++$i) {
$dateparameters []= $date[$i];
}
$year = $dateparameters[0];
$month = $dateparameters[1];
$actualmonth = $dateparameters[1];
$actualday = $dateparameters[2];
$actualdate = $year.'-'.$month.'-'.$actualday;
$day = cal_days_in_month(CAL_GREGORIAN, $month, $year);
$day = range(1, $day); // day range
$month = range(1, 12); // month range
if(in_array($actualday, $day) && in_array($actualmonth, $month)){ // Check if the actual month and day are within the valid range
$origin = date_create($actualdate); // Create the date of birth in proper date parameters
$target = date_create(date('Y-m-d')); // Create the current date
$age = date_diff($target, $origin);
$age = intval($age->format('%y'));
}
}
return $age;
}
?>
Applying the Function
Now that we have an improved validation function, let’s see how to apply it to calculate and display the age.
<?php
$birthdate = '2016-10-29';
$age = validate_date_and_get_age($birthdate);
if(!empty($age)){
echo 'Since you were born on '.$birthdate.', your age is: <b>'.$age.' years</b> old.';
} else {
echo $birthdate.' is an invalid date of birth.';
}
?>
Additional Ideas and Enhancements
- Date Input Form: Consider creating a user-friendly form where users can input their date of birth, and then use the validation and age calculation functions to display the result.
- Age Categories: Extend the functionality by categorizing age groups, such as child, teenager, adult, and senior. Display a relevant message based on the calculated age group.
- Date Format Validation: Enhance the date validation to handle different date formats or provide guidance on the expected format.
- Error Handling: Implement error handling to provide informative messages when the date of birth is not valid or the calculation encounters issues.
- Localization: Adapt the code to support different date formats and languages to make it more globally accessible.