Using filter_var() to verify date?
$myregex = '~^\d{2}/\d{2}/\d{4}$~';
The regex matched because you just require that pattern anywhere in the string. What you want is only that pattern and nothing else. So add ^
and $
.
Note that this still doesn't mean the value is a valid date. 99/99/9999
will pass that test. I'd use:
if (!DateTime::createFromFormat('d/m/Y', $string))
Using regex to validate date is a bad idea .. Imagine 99/99/9999
can easily be seen as a valid date .. you should checkdate
bool checkdate ( int $month , int $day , int $year )
Simple Usage
$date = "01/02/0000";
$date = date_parse($date); // or date_parse_from_format("d/m/Y", $date);
if (checkdate($date['month'], $date['day'], $date['year'])) {
// Valid Date
}
A simple and convenient way to verify the date in PHP is a strtotime function. You can validate the date with only one line:
strtotime("bad 01/02/2012 bad"); //false
strtotime("01/02/2012"); //1325455200 unix timestamp