当用户在文本框中输入日期时,我必须检查它是否为yyyy-mm-dd格式。
注意偶数月份、日期(例如:2012-02-32)无效,因为日期只能到31日,并且月份相同,他不能将月份输入为13。
如果格式不对,我应该回显。
提前感谢!
试试这个
list($year,$month,$day) = explode('-', $input);
if (checkdate($month, $day, $year)) {
// Correct
} else {
// Incorrect
}
阅读上的评论http://php.net/manual/en/function.checkdate.php内容丰富,包括通过regexp进行验证。
我使用该页面中的以下代码:
function checkDateTime($data) {
if (date('Y-m-d', strtotime($data)) == $data) {
return true;
} else {
return false;
}
}
此外,我建议添加JavaScript日期选择器http://jqueryui.com/demos/datepicker/
$e = explode('-', '2012-02-32');
if (checkdate($e[1], $e[2], $e[0])){
// Valid
}else{
// Invalid
}
http://php.net/manual/en/function.checkdate.php
这正是您所需要的:http://php.net/manual/en/function.checkdate.php
您不应该为此使用正则表达式。更好的(也许不是最好的)是使用checkdate();
$parts = explode('-', $input);
if (sizeof($parts) == 3 && checkdate($parts[1], $parts[2], $parts[0])) {
// Correct
} else {
// Incorrect
}