使用filter_var()验证日期? [英] Using filter_var() to verify date?
问题描述
我显然没有正确使用 filter_var().我需要检查用户是否以"dd/mm/yyyy"格式输入了有效日期.
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".
这只是返回我作为日期传递的内容,而我希望它返回日期或0/null/FALSE,以防输入字符串看起来不像日期:
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:
$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?
谢谢.
推荐答案
$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 $
.
请注意,这仍然并不意味着该值是有效日期. 99/99/9999
将通过该测试.我会用:
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))
这篇关于使用filter_var()验证日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!