validate date with php checkdate function (the new alternative method)

0
234
validate date with php checkdate function (the new alternative method)
validate date with php checkdate function (the new alternative method)

checkdate alternative special function validate date in php, such 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

testing if date is valid or invalid

 <?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';
}

?>

LEAVE A REPLY

Please enter your comment!
Please enter your name here