You Are Here: Home » How-To » Programming

How To Check If A Date Is Valid Using PHP In Codeigniter, CakePHP or Zend

By Debjit on December 29th, 2012 
Advertisement

User inputted data is something that should always be necessarily validated at the server side before storing it in the database. In this article we will tell you how to validate a date and check it on the server side using PHP. This date validation technique can be used very well in PHP based frameworks like codeigniter, cakePHP or zend.

PHP Valid / Invalid Date Checker

PHP Valid / Invalid Date Checker

This function given below checks for a date if it is valid or not. The function supports only the mm-dd-yyyy format of date. It takes two inputs - the Date and a separator which can be either "-" or "/" or any standard date separator character.

/*Function to check if a date is valid*/

function isValidDate($date, $separator) {

        if (count(explode($separator,$date)) == 3) {
$pattern = "/^([0-9]{2})".$separator."([0-9]{2})".$separator."([0-9]{4})$/";
if (preg_match ($pattern, $date, $parts))  {
if (checkdate($parts[1],$parts[2],$parts[3]))
return true;
/* This is a valid date */
else
return false;
/* This is an invalid date */
}  else  {
return false;
/* This is an invalid date in terms of format */
}
} else {
return false;
/* Day, Month, Year - either of them not present */
}

}

You can use this function in your codes and let me know if this works for you. Feel free to comment.

Advertisement







How To Check If A Date Is Valid Using PHP In Codeigniter, CakePHP or Zend was originally published on Digitizor.com on December 29, 2012 - 3:33 pm (Indian Standard Time)