dongranding3909 2018-08-15 15:27
浏览 86

检查日期错误:未定义的偏移量并且期望参数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?

  • 写回答

3条回答 默认 最新

  • doubu1964 2018-08-15 15:37
    关注

    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

    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题