[英]php time validation without zero in hours
I want to validate for a 24 hour format. 我想验证24小时格式。
The below code accepts 1:05:24 which is wrong, as it should instead only accept 01:05:24 下面的代码接受1:05:24这是错误的,因为它应该只接受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();
}
The following use of preg_match
will differentiate between the two cases you have mentioned. 以下对
preg_match
使用将区分您提到的两种情况。
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
. 但是,请注意,此问题或您在问题中提到的方法都不会正确检测到无效时间,例如
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
?>
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. 这将检查是否可以像在代码中一样创建日期,并且还可以确保格式为
H:i:s
的结果日期与用户输入的日期相对应。
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. 但是,就用户友好性而言,如果您可以根据用户输入创建日期,则最好接受日期并在缺少前导0时自己添加。 Simply use
$php_date
in favor of $item[1]
afterwards. 之后只需使用
$php_date
来支持$item[1]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.