检查日期错误:未定义的偏移量&期望参数1长,给定字符串

时间:2018-08-15 15:27:07

标签: php validation date datetime datepicker

我有一个输入日期字段:

<input type="date" id="date" name="date" />

默认情况下,如果用户未输入日期,则其中包含“ mm / dd / yyyy”。

我要检查发送的数据是否是有效日期:

//Assign the posted date to a variable.
$date = $_POST['date'];

//Explode the date to 3 parts 'mm', 'dd', 'yyyy'
$test_arr  = explode('/', $date);

//Check if $date is not valid date 'mm/dd/yyyy' [note the ! before each condition]
if ( !(checkdate($test_arr[0], $test_arr[1], $test_arr[2])) && !(preg_match("/^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/", $date)) )
{
    echo "Please enter a valid date";
}

如果用户提交时没有输入日期,那么我会得到一个空变量。

如果用户更改了输入并输入了字符或数字,或者为空,则出现以下错误:

Notice: Undefined offset: 1.
Notice: Undefined offset: 2.
checkdate() expects parameter 1 to be long, string given.

我可以检查它是否不为空,然后继续执行条件,但是如果我得到如下数据:('123','ijij','ioh3ihi33','bla bla'..),我会得到相同的结果错误。

如果日期无效,条件应打印一条消息。

那怎么办?

3 个答案:

答案 0 :(得分:0)

该小片段将检查发布的变量“日期”,并确保不仅格式有效,而且日期实际上也有效。

$date = ( isset( $_POST[ 'date' ] ) ? $_POST[ 'date' ] : '' );

if( preg_match( "/^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/", $date ) )
{

   //This is a valid date

}else{

  //Date is not valid

}

在这里玩正则表达式:

https://www.phpliveregex.com/p/oWb

答案 1 :(得分:0)

或者您可以使用strtotime函数

$valid = '01/31/2018';
var_dump(strtotime($valid)); // int(1517385600)
$invalid = '123/asd/asdklja213';
var_dump(strtotime($valid)); // bool(false);
  

注意:在PHP 5.1.0之前,此函数在失败时将返回-1。

答案 2 :(得分:0)

除非您知道字符串至少采用正确的格式,否则请不要调用checkdate()。它可能看起来不那么干净,但是您避免调用不需要知道的代码。

$date = $_POST['date'];

//Check if $date is not valid date 'mm/dd/yyyy'
if(preg_match("/^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/", $date))
{
    $test_arr  = explode('/', $date);

    if ( !(checkdate($test_arr[0], $test_arr[1], $test_arr[2])) )
    {
        echo "Please enter a valid date";
    }
}
else
{
    echo "Please enter a valid date";
}