碳(laravel)处理无效日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46828901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:49:51  来源:igfitidea点击:

Carbon (laravel) deal with invalid date

phplaravelexceptionerror-handlingphp-carbon

提问by Nemo Grippa

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

我有一个非常简单的问题.. 我使用该Carbon::parse($date)函数与$date = '15.15.2015'. 当然它不能返回一个有效的字符串,因为没有第 15 个月。但是我怎么能“忽略”错误信息呢?伟大的将是这样的

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

回答by Tudor

You can catch the exception raised by Carbon like this:

您可以像这样捕获 Carbon 引发的异常:

try {
    Carbon::parse($date);
} catch (\Exception $e) {
    echo 'invalid date, enduser understands the error message';
}

回答by aaron0207

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

在使用之前通过Laravel 的验证。创建一个这样的验证器:

     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

您可以将所有所需的字段添加到验证器并应用多个验证来处理每条消息或使用默认消息。如果您正在验证用户的输入,这将是方式