Carbon(laravel)处理无效日期 [英] Carbon (laravel) deal with invalid date

查看:182
本文介绍了Carbon(laravel)处理无效日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的问题。.我使用 Carbon :: parse($ date)函数和 $ date = '15 .15.2015 '。当然,因为没有第15个月,它不能返回有效的字符串。但是我如何忽略错误消息?
太好了,例如

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';


推荐答案

通过 Laravel的验证,然后再使用。创建像这样的验证器:

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

这篇关于Carbon(laravel)处理无效日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆