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

I have an input date field:

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

By default if the user didn't enter a date, It contains "mm/dd/yyyy".

I want to check that the sent data is a valid date:

//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";
}

If the user submit without entering a date, Then I get an empty variable.

If the user changed the input and entered characters or digits, Or empty, I get the following errors:

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

I could check if it's not empty, then continue to the conditions, But if I get data like: ('123', 'ijij', 'ioh3ihi33', 'bla bla' ..), I would get the same errors.

The conditions should print a message in case of invalid date.

So how to do that?

This little snippet will check for a posted variable "date" and ensure not only the format is valid, but the date is actually valid too.

$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

}

Have a play with the regex here:

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

Or you could use strtotime function

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

Note: Previous to PHP 5.1.0, this function would return -1 on failure.

Don't call checkdate() unless you know that the string is at least in the correct format. It might not look as clean, but you avoid calling code that you know doesn't need to be called.

$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";
}