Carbon (laravel) deal with invalid date

前端 未结 4 1946
面向向阳花
面向向阳花 2021-02-20 05:22

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

相关标签:
4条回答
  • 2021-02-20 05:57

    You can catch the exception raised by Carbon like this:

    try {
        Carbon::parse($date);
    } catch (\Exception $e) {
        echo 'invalid date, enduser understands the error message';
    }
    
    0 讨论(0)
  • 2021-02-20 06:00

    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

    0 讨论(0)
  • 2021-02-20 06:09

    Try this

    $birth_date = Carbon::createFromFormat('dmy', $birth_date_mark)->startOfDay();
    if ($birth_date->format('dmy') !== $birth_date_mark) {
         throw new OperationException(trans('exception.invalid_birth_date'));
    }
    
    0 讨论(0)
  • 2021-02-20 06:10

    another solution would be to handle the exception globally.

    • in app/Exceptions/Handler.php
    use Carbon\Exceptions\InvalidFormatException;
    
    • then in the render method check if an exception is thrown by Carbon
        if ($exception instanceof InvalidFormatException) {
                return response()->json([
                    'status' => 'fail',
                    'data' => [
                        'message' => 'Invalid date formate!'
                    ]
                ], 400);
            }
    
    0 讨论(0)
提交回复
热议问题