Nem*_*ppa 5 php error-handling exception laravel php-carbon
我有一个很简单的问题..我用的是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';
Run Code Online (Sandbox Code Playgroud)
Tud*_*dor 11
您可以像这样捕获Carbon引发的异常:
try {
Carbon::parse($date);
} catch (\Exception $e) {
echo 'invalid date, enduser understands the error message';
}
Run Code Online (Sandbox Code Playgroud)
在使用之前,请先通过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);
}
Run Code Online (Sandbox Code Playgroud)
并在使用您的约会日期之前给他打电话:
$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);
Run Code Online (Sandbox Code Playgroud)
您可以将所有所需的字段添加到验证器,并应用多个验证来处理每条消息或使用默认消息。如果您要验证用户的输入,这将是这种方式
| 归档时间: |
|
| 查看次数: |
9287 次 |
| 最近记录: |