michaelmcgurk
michaelmcgurk

Reputation: 6509

Why does my Date return false with regular expression?

This is the regular expression I am using:

if (preg_match("/^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/", $_POST["collection-date"]) === 0) {
        $errors .= "\n Error: Invalid Collection Date";
        $collectiondate = FALSE;
    }

Currently $_POST['collection-date'] equals 15/02/2012 and it still returns false. Why is this?

Thank you for any suggestions.

Upvotes: 0

Views: 72

Answers (2)

null
null

Reputation: 11859

I've checked this regular expression and it works.

I have small advice to you, don't check number of matches in preg_match() (I've commonly seen this). It's very confusing, trust me. == 0 means if it wasn't found. Personally, I just use it in boolean content, even if preg_match() returns integer (number of matches) and not boolean. But it's not really important - 0 in PHP is false and other integers are true in boolean context. It usually matches with your expectations in this case - 0 matches usually means fail.

Second, there is no assignment to $collectiondate other than false. I don't know if it is intentional, but if you never send any positive value, it's usually null or false. In boolean context, both of those values return false. In fact, false == null because of null being converted to boolean (but false !== null, because !== skips any conversions (it's good idea to use === instead of == for reasons mentioned in https://stackoverflow.com/a/80649/736054)).

Upvotes: 1

Mike
Mike

Reputation: 24383

$split = explode('/', $date);
if (!isset($split[2]) || !checkdate($split[1],$split[0],$split[2])) {
    $errors .= "\n Error: Invalid Collection Date";
    $collectiondate = FALSE;
}

This also validates false if someone enters an invalid date, such as 99/99/2012 or 31/02/2012, which you probably want as well.

Upvotes: 3

Related Questions