php中的日期格式验证

时间:2014-05-20 10:35:45

标签: php validation date date-format

我制作了一个有3个字段的表格,其中一个是出生日期。我想检查日期的格式为yyyy-mm-dd。到目前为止,我设法做到了这一点:

检查$_POST vars已设置,如果缺少则退出。

if(!isset($_POST["name"]) || !isset($_POST["surname"]) || !isset($_POST["date_of_birth"]))
{
    $output = json_encode(array('type'=>'error', 'text' => 'Input fields are empty!'));
    die($output);
}

//Sanitize input data using PHP filter_var().
$name       = filter_var($_POST["name"], FILTER_SANITIZE_STRING);
$surname       = filter_var($_POST["surname"], FILTER_SANITIZE_EMAIL);
$date_of_birth    = filter_var($_POST["date_of_birth"], FILTER_SANITIZE_STRING);
$date_regex = '/^(19|20)\d\d[\-\/.](0[1-9]|1[012])[\-\/.](0[1-9]|[12][0-9]|3[01])$/';
$date = '2013-04-14';

//additional php validation
if(strlen($name)<3) // If length is less than 3 it will throw an HTTP error.
{
    $output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
    die($output);
}
if(strlen($surname)<3) // If length is less than 3 it will throw an HTTP error.
{
    $output = json_encode(array('type'=>'error', 'text' => 'Surname is too short or empty!'));
    die($output);
}
if (!preg_match($date_regex, $date)) //check entered data is numbers
{
    $output = json_encode(array('type'=>'error', 'text' => 'Only yyyy-mm-dd format is allowed'));
    die($output);
}

问题是,在验证日期时,我总是会收到错误,说我输入了错误的日期格式,即使我输入正确也是如此。你能告诉我哪里弄错了吗?

谢谢。

2 个答案:

答案 0 :(得分:0)

$date = '2013-04-14';
if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",$date)) 
echo 'correct';
else
echo 'incorrect';

答案 1 :(得分:0)

    $date = "2014-05-06";
    if (date('Y-m-d', strtotime($date)) == $date) print_r('valid');