php日期验证


php date validation

我试图设置php日期验证(MM/DD/YYYY),但遇到了问题。这是我得到的一个样本:

$date_regex = '%'A(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)'d'd'z%'; 
$test_date = '03/22/2010'; 
if (preg_match($date_regex, $test_date,$_POST['birthday']) ==true) {
    $errors[] = 'user name most have no spaces';`

您可以使用checkdate。例如,类似这样的东西:

$test_date = '03/22/2010';
$test_arr  = explode('/', $test_date);
if (checkdate($test_arr[0], $test_arr[1], $test_arr[2])) {
    // valid date ...
}

一种更偏执的方法,不盲目相信输入:

$test_date = '03/22/2010';
$test_arr  = explode('/', $test_date);
if (count($test_arr) == 3) {
    if (checkdate($test_arr[0], $test_arr[1], $test_arr[2])) {
        // valid date ...
    } else {
        // problem with dates ...
    }
} else {
    // problem with input ...
}

您可以使用DateTime类的一些方法,这可能很方便;即CCD_ 2与CCD_。

$test_date = '03/22/2010';
$date = DateTime::createFromFormat('m/d/Y', $test_date);
$date_errors = DateTime::getLastErrors();
if ($date_errors['warning_count'] + $date_errors['error_count'] > 0) {
    $errors[] = 'Some useful error message goes here.';
}

这甚至可以让我们看到日期解析警告/错误的实际原因(看看$date_errors中的warningserrors数组)。

虽然checkdate很好,但这似乎是一个非常简洁的验证函数,而且您还可以提供格式。[来源]

function validateDate($date, $format = 'Y-m-d H:i:s') {
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) == $date;
}

函数是从这个答案或php.net复制的


对于日期无效但createFromFormat仍能创建DateTime对象的情况,需要额外的->format()。例如:

// Gives "2016-11-10 ..." because Thursday falls on Nov 10
DateTime::createFromFormat('D M j Y', 'Thu Nov 9 2016');
// false, Nov 9 is a Wednesday
validateDate('Thu Nov 9 2016', 'D M j Y');

而不是庞大的DateTime对象。。只需使用核心日期()函数

function isValidDate($date, $format= 'Y-m-d'){
    return $date == date($format, strtotime($date));
}

使用它:

function validate_Date($mydate,$format = 'DD-MM-YYYY') {
    if ($format == 'YYYY-MM-DD') list($year, $month, $day) = explode('-', $mydate);
    if ($format == 'YYYY/MM/DD') list($year, $month, $day) = explode('/', $mydate);
    if ($format == 'YYYY.MM.DD') list($year, $month, $day) = explode('.', $mydate);
    if ($format == 'DD-MM-YYYY') list($day, $month, $year) = explode('-', $mydate);
    if ($format == 'DD/MM/YYYY') list($day, $month, $year) = explode('/', $mydate);
    if ($format == 'DD.MM.YYYY') list($day, $month, $year) = explode('.', $mydate);
    if ($format == 'MM-DD-YYYY') list($month, $day, $year) = explode('-', $mydate);
    if ($format == 'MM/DD/YYYY') list($month, $day, $year) = explode('/', $mydate);
    if ($format == 'MM.DD.YYYY') list($month, $day, $year) = explode('.', $mydate);       
    if (is_numeric($year) && is_numeric($month) && is_numeric($day))
        return checkdate($month,$day,$year);
    return false;           
}         

REGEX应该是最后的手段。PHP有几个函数可以为您进行验证。在您的情况下,checkdate是最好的选择。http://php.net/manual/en/function.checkdate.php

Nicolas解决方案是最好的。如果你想在regex,

试试这个,

这将验证,从1900年1月1日到2099年12月31日匹配无效日期,如2月31日接受短划线、空格、正斜杠和点作为日期分隔符

(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)[0-9]{2}

此功能运行良好,

function validateDate($date, $format = 'm/d/Y'){
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) === $date;
}

我知道这是一篇旧帖子,但我已经开发了以下验证日期的功能:

function IsDateTime($aDateTime) {
    try {
        $fTime = new DateTime($aDateTime);
        $fTime->format('m/d/Y H:i:s');
        return true;
    }
    catch (Exception $e) {
        return false;
    }
}

试试这个

/^(19[0-9]{2}|2[0-9]{3})'-(0[1-9]|1[0-2])'-(0[1-9]|1[0-9]|2[0-9]|3[0-1])((T|'s)(0[0-9]{1}|1[0-9]{1}|2[0-3]{1})':(0[0-9]{1}|1[0-9]{1}|2[0-9]{1}|3[0-9]{1}|4[0-9]{1}|5[0-9]{1})':(0[0-9]{1}|1[0-9]{1}|2[0-9]{1}|3[0-9]{1}|4[0-9]{1}|5[0-9]{1})(('+|'.)['d+]{4,8})?)?$/

此正则表达式有效于:

  • 2017-01-01 00:00:00+0000
  • 2017-01-01 00:00:00+00:00
  • 2017-01-01 00:00:00+00:00
  • 2017-01-01 00:00:00+0000
  • 2017-01-01

请记住,这将涵盖所有带有(-)字符

的日期和日期时间的情况

不确定这是否能回答问题或有帮助。。。。

$dt = '6/26/1970' ; // or // '6.26.1970' ;
$dt = preg_replace("([.]+)", "/", $dt);
$test_arr  = explode('/', $dt);
if (checkdate($test_arr[0], $test_arr[1], $test_arr[2]) && preg_match("/[0-9]{1,2}'/[0-9]{1,2}'/[0-9]{4}/", $dt))
     { echo(date('Y-m-d', strtotime("$dt")) . "<br>"); }
   else
     { echo "no good...format must be in mm/dd/yyyy"; }

我们可以使用简单的"日期"输入类型,如下所示:

Birth date: <input type="date" name="userBirthDate" /><br />

然后我们可以将DateTime接口与内置功能"爆炸"链接起来:

public function validateDate()
    {
        $validateFlag = true;
        $convertBirthDate = DateTime::createFromFormat('Y-m-d', $this->birthDate);
        $birthDateErrors = DateTime::getLastErrors();
        if ($birthDateErrors['warning_count'] + $birthDateErrors['error_count'] > 0)
        {
            $_SESSION['wrongDateFormat'] = "The date format is wrong.";
        }
        else
        {
            $testBirthDate = explode('-', $this->birthDate);
            if ($testBirthDate[0] < 1900)
            {
                $validateFlag = false;
                $_SESSION['wrongDateYear'] = "We suspect that you did not born before XX century.";
            }
        }
        return $validateFlag;
    }

我在谷歌浏览器和IE上测试过,一切都正常。此外,Chrome显示简单的附加界面。如果您没有在输入中写入任何内容或以错误的格式写入(正确的格式如下:"1919-12-23"),您将获得第一条语句。如果你把所有的东西都写得很好,但你键入了错误的日期(我认为没有人能在XX世纪之前出生),你的控制器会发送第二条声明。

我认为它会帮助一些人

function isValidDate($thedate) {
    $data = [
        'separators' => array("/", "-", "."),
        'date_array' => '',
        'day_index' => '',
        'year' => '',
        'month' => '',
        'day' => '',
        'status' => false
    ];
    // loop through to break down the date
    foreach ($data['separators'] as $separator) {
        $data['date_array'] = explode($separator, $thedate);
        if (count($data['date_array']) == 3) {
            $data['status'] = true;
            break;
        }
    }
    // err, if more than 4 character or not int
    if ($data['status']) {
        foreach ($data['date_array'] as $value) {
            if (strlen($value) > 4 || !is_numeric($value)) {
                $data['status'] = false;
                break;
            }
        }
    }
    // get the year
    if ($data['status']) {
        if (strlen($data['date_array'][0]) == 4) {
            $data['year'] = $data['date_array'][0];
            $data['day_index'] = 2;
        }elseif (strlen($data['date_array'][2]) == 4) {
            $data['year'] = $data['date_array'][2];
            $data['day_index'] = 0;
        }else {
            $data['status'] = false;
        }
    }
    // get the month
    if ($data['status']) {
        if (strlen($data['date_array'][1]) == 2) {
            $data['month'] = $data['date_array'][1];
        }else {
            $data['status'] = false;
        }
    }
    // get the day
    if ($data['status']) {
        if (strlen($data['date_array'][$data['day_index']]) == 2) {
            $data['day'] = $data['date_array'][$data['day_index']];
        }else {
            $data['status'] = false;
        }
    }
    // finally validate date
    if ($data['status']) {
        return checkdate($data['month'] , $data['day'], $data['year']);
    }
    return false;
}