PHP date validation

Validating a date using PHP is pretty straightforward and easy and there are plenty of methods out there of doing this, but I want to show you a few of my own methods.

The function below takes two strings as parameters, $date (e.g.: 12/13/2012) and $format (valid date formats), the latter being optional.

function is_valid_date($date, $format = 'm/d/Y')
{
  return date( $format, strtotime($date) ) == $date;
}

is_valid_date('13/12/2012'); // true
is_valid_date('02/30/2012'); // false

Note that you MUST use one of the valid date formats found on this page: http://www.php.net/manual/en/datetime.formats.date.php, otherwise the function won’t work.

The downside of the function above is that it can only validate one format at a time.

But with a few changes we can make it validate more formats at a time:

function is_valid_date( $date, $format = array('m/d/Y', 'm/d/y', 'n/j/Y', 'n/j/y', 'n/d/Y', 'n/d/y', 'm/j/Y', 'm/j/y') )
{
  // If the $format parameter is not an array, then make it an array.
  if ( !is_array($format) )
    $format = array($format);

  // Go through each format.
  foreach ($format as $value)
    // If a date is valid for one format there is no point in continuing.
    if ( date( $value, strtotime($date) ) == $date )
      return true;

  return false;
}

Now, with the function above, we can validate all these formats:

mm/dd/yyyy
mm/dd/yy
m/d/yyyy
m/d/yy
m/dd/yyyy
m/dd/yy
mm/d/yyyy
mm/d/yy

Here are a few examples:

is_valid_date('2/06/2012'); // true
is_valid_date('2/6/2012'); // true
is_valid_date('02/6/2012'); // true
is_valid_date('2/28/2012'); // true
is_valid_date('2/30/2012'); // false

It may not be the shortest function to validate dates like mm/dd/yyyy, but it is a bit more flexible, allowing you to adapt it to other formats, by changing the $format parameter.

Leave a Reply