Reputation: 1498
I want to validate for a 24 hour format.
The below code accepts 1:05:24 which is wrong, as it should instead only accept 01:05:24
try
{
foreach ($arr as $key=>$item)
{
if (date('H:i:s', strtotime($item[1])))
{
} else {
throw new Exception('Invalid Time Format');
}
}
}
catch (Exception $e)
{
echo $exp = $e->getMessage();
}
Upvotes: 0
Views: 82
Reputation: 2180
Based on the code you've provided, one way would be the following:
$php_date = date('H:i:s', strtotime($item[1]));
if ($php_date && $php_date == $item[1]) {
// valid date
}
This will check that a date could be created as in your code, and it will also ensure that the resulting date in the format H:i:s
corresponds to what the user entered.
However, in terms of user-friendliness, if you can create a date from the user input, it might be better just to accept it and add the leading 0 yourself if it is missing. Simply use $php_date
in favor of $item[1]
afterwards.
Upvotes: 0
Reputation: 75555
The following use of preg_match
will differentiate between the two cases you have mentioned.
However, note that neither this nor the method that you mentioned in the question will correctly detect an invalid time such as 00:99:99
.
If you require that, you need a different method, the easiest of which is probably to parse out the numbers and run this function on it.
<?php
$mydate_bad = "1:05:70";
$mydate_good = "01:05:24";
print (preg_match("/^\d\d:\d\d:\d\d$/", $mydate_bad)); # Returns 0
print (preg_match("/^\d\d:\d\d:\d\d$/", $mydate_good)); # Returns 1
?>
Upvotes: 2