Date format validation in PHP

Posted on May 11, 2008 
Filed Under php, tutorial

Today Sushil asked me how can we validate the date which is entered from textbox in “YYYY-MM-DD” format. Well, we can validate the format of the date using regular expression but how to validate weather that date is valid date or not, such as “2007-02-29″ is the correct format of the date but it’s not the valid date.

To overcome that situation, I’ve used checkdate() function available in PHP for validation of date.

Function to validate date format in PHP

function checkDateFormat($date)
{
  //match the format of the date
  if (preg_match ("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date, $parts))
  {
    //check weather the date is valid of not
	if(checkdate($parts[2],$parts[3],$parts[1]))
	  return true;
	else
	 return false;
  }
  else
    return false;
}

In the above function, first of all format of date is validated using regular expression. As you can see the in the preg_match() function, there are three expression each separated by “-” and there can be only digits of length of 4,2 and 2 in these expressions. If the date format is incorrect then this function returns “false” value. And, if the supplied string contains the valid date format then the part matching each expression are stored in the “$parts” array. Such as, if we supply “2007-03-12″ then “2007″, “03″ and “12″ are stored in the “$parts” array. After that, checkdate() function of PHP is used check weather the supplied date is valid date or not.

Example

echo checkDateFormat("2008-02-29"); //return true
echo checkDateFormat("2007-02-29"); //return false

Popularity: 9% [?]

If you like this post then please subscribe to my full RSS feed . You can also subscribe by email and have new posts sent directly to your inbox.And, You can also follow me on twitter at http://twitter.com/roshanbh.

Related Posts

» Solving time difference between hosting server and local timezone in PHP
» Finding difference of days between two dates in PHP
» Ip address validation in PHP using regular expression
» USA’s Zip Code Validation in PHP

Comments

2 Responses to “Date format validation in PHP”

  1. Suresh on May 12th, 2008 7:09 pm

    I used checkdate() to validate date in format ‘YYYY-mm-dd’ . but i can’t able to get the expect result . Now i am using Javascript to validate date.

  2. Roshan on May 13th, 2008 10:55 am

    You can’t rely on the validation of javascript, as it can be bypassed by disabling javascript in browser and that function was working perfectly for various supplied data……can you please post the dates from which you’ve got bad or wrong result..

Leave a Reply