douqi3913 2017-10-19 11:31
浏览 44
已采纳

Carbon(laravel)处理无效日期

I have a quite simple problem.. I use the Carbon::parse($date) function with $date = '15.15.2015'. Of course it can not return a valid string because there is no 15th month. But how can i "ignore" the error message? Great would be something like

if (Carbon::parse($date) != error) Carbon::parse($date);
else echo 'invalid date, enduser understands the error message';
  • 写回答

2条回答 默认 最新

  • douxian0008 2017-10-19 11:43
    关注

    Pass Laravel's validation before use it. Create a validator like this:

         protected function validator(array $data)
    {
        //$data would be an associative array like ['date_value' => '15.15.2015']
        $message = [
            'date_value.date' => 'invalid date, enduser understands the error message'
        ];
        return Validator::make($data, [
            'date_value' => 'date',
        ],$message);
    }
    

    And call him right before use your date:

    $this->validator(['date_value' => $date])->validate();
    // $this->validator(request()->all())->validate(); you can pass the whole request if fields names are the same
    
    Carbon::parse($date);
    

    You can add all your desired fields to validator and apply multiple validations handling every message or using the default message. This would be the way if you are validating User's input

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 SQL Server下载
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求