0

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.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
michaelmcgurk
  • 6,367
  • 23
  • 94
  • 190

2 Answers2

3
$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.

Mike
  • 23,542
  • 14
  • 76
  • 87
  • 1
    You could also add `|| isset($split[3])` to that `if` statement as well in case someone enters `15/02/2012/someotherstuffhere` if necessary, or just use the variables from `$split` and forget about anything after if they add another slash and more content. – Mike Feb 15 '12 at 20:22
  • Many, many thanks Mike. Your solution did the trick. Now to read Glitch's comments :-) – michaelmcgurk Feb 15 '12 at 20:38
1

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)).

Community
  • 1
  • 1
Konrad Borowski
  • 11,584
  • 3
  • 57
  • 71