I'm trying to use preg_match
to validate that a time input is in this format - "HH:MM"
You can use regular expressions to check that.
for 12-hour:
preg_match("/^(?:1[012]|0[0-9]):[0-5][0-9]$/", $foo)
for 24-hour:
preg_match("/^(?:2[0-3]|[01][0-9]):[0-5][0-9]$/", $foo)
If you use a 24-hour clock going from 01:00 to 24:59, use
preg_match("/^(?:2[0-4]|[01][1-9]|10):([0-5][0-9])$/", $foo)
Simple function that validates a date (and/or time) without throwing exceptions. It takes the expected date format as a parameter:
function isValidDate(string $date, string $format = 'Y-m-d'): bool
{
$dateObj = DateTime::createFromFormat($format, $date);
return $dateObj && $dateObj->format($format) == $date;
}
How it works: it converts the input date into a PHP DateTime
object according to the passed $format
, then compares this object with the original input date.
If they match, the date is valid and has the expected format.
Some usage examples:
/* Valid Examples: */
isValidDate("2017-05-31");
isValidDate("23:15:00", 'H:i:s');
isValidDate("2017-05-31 11:15:00", 'Y-m-d h:i:s');
/* Invalid: */
isValidDate("2012-00-21");
isValidDate("25:15:00", 'H:i:s');
isValidDate("Any string that's not a valid date/time");
Let's imagine the time you want to check is $timeStr
and has to be the format H:i
according to the date specs.
Using a regex for this is IMHO silly. This is so much easier to read:
UPDATED
$timeStr = " 02:00"; //example of valid time, note whitespace
test($timeStr);
$timeStr = "23:59"; //valid
test($timeStr);
$timeStr = "24:00"; //invalid
test($timeStr);
$timeStr = "25:00"; //invalid
test($timeStr);
$timeStr = "16:61"; // invalid
test($timeStr);
//tests 23:59 hour format
function test($timeStr){
$dateObj = DateTime::createFromFormat('d.m.Y H:i', "10.10.2010 " . $timeStr);
if ($dateObj !== false && $dateObj && $dateObj->format('G') ==
intval($timeStr)){
//return true;
echo 'valid <br/>';
}
else{
//return false;
echo 'invalid <br/>';
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With