php 使用 filter_var() 来验证日期?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13746332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:00:38  来源:igfitidea点击:

Using filter_var() to verify date?

phpfiltering

提问by Gulbahar

I'm obviously not using filter_var()correctly. I need to check that the user has entered a valid date, in the form "dd/mm/yyyy".

我显然没有正确使用filter_var()。我需要检查用户是否输入了有效日期,格式为“dd/mm/yyyy”。

This simply returns whatever I passed as a date, while I expected it to return either the date or 0/null/FALSE in case the input string doesn't look like a date:

这只是返回我作为日期传递的任何内容,而我希望它返回日期或 0/null/FALSE,以防输入字符串看起来不像日期:

$myregex = "/\d{2}\/\d{2}\/\d{4}/";
print filter_var("bad 01/02/2012 bad",FILTER_VALIDATE_REGEXP,array("options"=>array("regexp"=> $myregex)));

If someone else uses this function to check dates, what am I doing wrong? Should I use another function to validate form fields?

如果其他人使用此功能检查日期,我做错了什么?我应该使用另一个函数来验证表单域吗?

Thank you.

谢谢你。

回答by Baba

Using regex to validate date is a bad idea .. Imagine 99/99/9999can easily be seen as a valid date .. you should checkdate

使用正则表达式来验证日期是一个坏主意..试想一下,99/99/9999可以很容易地被看作是一个有效的日期..你应该了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
}

回答by deceze

$myregex = '~^\d{2}/\d{2}/\d{4}$~';

The regex matched because you just require that pattern anywherein the string. What you want is onlythat pattern and nothing else. So add ^and $.

正则表达式匹配,因为您只需要在字符串中的任何位置使用该模式。你想要的只是那个模式,没有别的。所以添加^$

Note that this still doesn't mean the value is a valid date. 99/99/9999will pass that test. I'd use:

请注意,这仍然并不意味着该值是一个有效的 date99/99/9999将通过该测试。我会用:

if (!DateTime::createFromFormat('d/m/Y', $string))

回答by Tim

Why using a heavy RegEx, while there is a native DateTimePHP-class?

为什么使用繁重的 RegEx,而有一个原生的DateTimePHP 类?

$value = 'badbadbad';

try {
    $datetime = new \DateTime($value);

    $value = $datetime->format('Y-m-d');
} catch(\Exception $e) {
    // Invalid date
}

Always returns the format you were expecting, if a valid datetime string was inserted.

如果插入了有效的日期时间字符串,则始终返回您期望的格式。

回答by Cmyker

A simple and convenient way to verify the date in PHP is a strtotimefunction. You can validate the date with only one line:

在 PHP 中验证日期的一种简单方便的方法是strtotime函数。您可以只用一行来验证日期:

strtotime("bad 01/02/2012 bad"); //false
strtotime("01/02/2012"); //1325455200 unix timestamp

回答by Benjamin Paap

Try setting the start and end for your regex like this:

尝试像这样设置正则表达式的开始和结束:

$myregex = "/^\d{2}\/\d{2}\/\d{4}$/";

回答by Zauker

The better solution is posted by @baba, but the code posted doesn't work fine in certain conditions.

@baba 发布了更好的解决方案,但发布的代码在某些情况下无法正常工作。

For example if you try to validate this date "2019-12-313";

例如,如果您尝试验证此日期“2019-12-313”;

$date = date_parse("2019-12-313");

the function returns this array:

该函数返回这个数组:

Array
(
    [year] => 2019
    [month] => 12
    [day] => 31
    [hour] => 
    [minute] => 
    [second] => 
    [fraction] => 
    [warning_count] => 0
    [warnings] => Array
        (
        )

    [error_count] => 1
    [errors] => Array
        (
            [10] => Unexpected character
        )

    [is_localtime] => 
)

so, if you perform the command:

所以,如果你执行命令:

checkdate($date['month'], $date['day'], $date['year']);

checkdate will returns a true value because the value of $date['day']is 31 instead of 313.

checkdate 将返回一个真值,因为 的值$date['day']是 31 而不是 313。

to avoid this case maybe you have to add a check to the value of $date['error_count']

为了避免这种情况,也许你必须添加一个检查的值 $date['error_count']

the @baba example updated

@baba 示例已更新

$date = "2019-12-313";
$date = date_parse($date); // or date_parse_from_format("d/m/Y", $date);
if ($date['error_count'] == 0 && checkdate($date['month'], $date['day'], $date['year'])) {
    // Valid Date
}

回答by AJ Quick

You received a lot of answers that indicated the RegEx would allow for an answer of 99/99/9999. That can be solved by adding a little more to the RegEx. If you know you'll never have a date outside of the years 1900-2099... you can use a RegEx like this:

您收到了很多答案,这些答案表明 RegEx 将允许 99/99/9999 的答案。这可以通过向 RegEx 添加更多内容来解决。如果你知道你永远不会有 1900-2099 年之外的日期......你可以使用这样的正则表达式:

/^(0[1-9]|[12][0-9]|3[01])[/](0[1-9]|1[012])[/](19|20)\d\d$/

That will validate a date of this format: dd/mm/YYYY

这将验证此格式的日期:dd/mm/YYYY

Between: 01/01/1900 - 31/12/2099

之间:01/01/1900 - 31/12/2099

If you need more years, just add them near the end. |21|22|23|24|25 (would extend it to the year 2599.)

如果您需要更多年,只需在接近尾声时添加它们。|21|22|23|24|25(将其扩展到 2599 年。)