Best PHP checkdate alternative: How to do date validation in php (exclusive)

this checkdate alternative special function validates date in such a way that is simpler and authentic

without using the actual php date validation function checkdate()

we used on range and in_array function to create this special function to validate date

the function checks if the day is contained in a given month within the range specified in the year of the given date

like if 31 contained in a date assuming 1998-02-31

it will output invalid
Why!

Because range provided by month 02 (february) is between the range 1-29 the number of days found in february and it does not contain 31

1st code for the checkdate alternative

 
<?php 
function validate_date($date){
	$dateparameters = array();
	$date = preg_replace("/[^0-9\']/", ",", $date);	
	$date = explode(',', $date);
	$validation = '';
	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];
	$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 actual month and day is in range of days that should be in the provided month of the given year
		$validation = 'valid';
	}
		
	}
return $validation;
}
?>

let’s apply the function

In your web application development job you wish to valid date using this special function

just do as I did below

How to apply this checkdate function

I programmed a logic that does one thing if the date is valid or invalid

 <?php
$ourdate = "2022/7/34"; //our provided date
if(validate_date($ourdate) == 'valid'){
	echo $ourdate.' is a valid date';
}else{
	echo $ourdate.' is an invalid date';
}
?>

Very important the date format to use must be in the format yyyy-mm-dd or yyyy/mm/dd regardleass of the date parameter seperators

the above code should output “2022/7/34 is an invalid date”

Let’s test this date 1994-02-14 using the logic above

 <?php
$ourdate = "1994-02-14"; //our provided date
if(validate_date($ourdate) == 'valid'){
	echo $ourdate.' is a valid date';
}else{
	echo $ourdate.' is an invalid date';
}

?>

Related

How TO create a Login Form (w3schools vs bootstrap)

Every transactional website should have a login form that...

How to validate date of birth today & get the age from the birthday using php

we have already explained how you can get age...

How to use php to check age for birthday messages

We going to check age for birthday messages using...

How to check product expiration duration of any product using php (2 proven function)

with this simple php trick you can check expiration...

the 2 easy ways to create dynamic form inputs in php

these are 2 ways you can create dynamic form...