views:

147

answers:

3

What would the regex expression that would go into preg_split function to validate date in the format of

7-Mar-10 or how can I validate a date of format 7-Mar-10 in PHP

Thanks.

+7  A: 

strtotime?

And here's an example of how to use it

function isValidTime($str) {
    return strtotime($str) !== false;
}
zneak
No. I am looking for validation logic, let's say if I would have Hello World instead of data than what would strtotime give ?
Rachel
@Rachel: It would return `false`, which you can assert: `if(strtotime($date) === false) // it's not a valid date`
zneak
@Rachel: *“Returns a timestamp on success, FALSE otherwise. Previous to PHP 5.1.0, this function would return -1 on failure.”*
Joey
@Rachel, see what happens: `if(strtotime("hello world")) { ...`
Bart Kiers
Rachel `strtotime` *is* useful for validation. I've added an example to zneak's answer on how to use this (I didn't want to steal his thunder with a duplicate answer of my own).
Justin Johnson
A: 

I'd make it first with explode,

$parts=explode("-",$date);

then with array

$months=array("Jan"=>1,"Feb"=>2...)

and then use checkdate($months[$parts1],$parts[0],$parts[2]);

Col. Shrapnel
That's way more verbose than necessary.
Justin Johnson
A: 

The DateTime class's createFromFormat method (also available in function form) allows one to parse a date string against a given format. The class also has the benefit of keeping track of errors for you should you want see what went wrong.

Here's a quick yay/nay validation function:

function valid($date, $format = 'j-M-y') {
    $datetime = DateTime::createFromFormat($format, $date, new DateTimeZone('UTC'));
    $errors   = DateTime::getLastErrors();
    return ($errors['warning_count'] + $errors['error_count'] === 0);
}

var_dump(valid('7-Mar-10')); // bool(true)
var_dump(valid('7-3-10'));   // bool(false)

Of course, the above is only for validating a single format of date (and only available as of PHP 5.3) so if you are just wanting to accept any date (even 'wrong' dates that get automatically converted to the right value), or for whatever reason cannot yet use PHP 5.3, then as mentioned in other answers, strtotime would be of assistance.

salathe