自定义验证在Laravel 5.4中不起作用

时间:2019-01-28 12:04:33

标签: validation date laravel-5.4

正在开发Laravel应用程序,从而正在进行两个日期的后端验证。这两个日期分别主要是离开日期和返回日期。

在出发日期,我试图验证其是否必需,该日期应为date类型,并且应为今天之后的日期。在返还日期时,我还尝试实现一种验证逻辑,即返还日期应在出发日期之后3天或更长时间,但应在出发日期之后180天以内。

验证功能

 public function validateDates(Request $request){   
        //dd($request->all());
     $now = new \DateTime();

    $after_date = $now->parse($this->departureDate)->addDays(3);
    $maxdays = $now->parse($this->departureDate)->addDays(180);

        $validation = $this->validate($request, [
          'departureDate' => 'required|date|after:now',
          'returnDate' => 'required|date_format:"Y-m-d"|after:' . $after_date->toDateString().'|before:' . $maxdays->toDateString()
        ], 
        [
            'departureDate.after' => 'Your departure date should be tomorrow or any date in the future',
           'returnDate.after' => 'Your return date should be 3 or more days after the departure date',
           'returnDate.before' => 'Your return date should be no more than 180 days from the departure date',
        ]
    };

1 个答案:

答案 0 :(得分:0)

我认为您的逻辑很好。但是,您可能正在寻找使用Carbon来代替。它具有您要寻找的parse()方法。还有addDays()toDateString()

因此,在文件顶部,添加以下语句:

use Carbon\Carbon; 

,然后将您的validateDate()方法更改为此:

public function validateDates(Request $request)
{   
    $after_date = Carbon::parse($this->departureDate)->addDays(3)->toDateString();
    $max_days   = Carbon::parse($this->departureDate)->addDays(180)->toDateString();

    $validation = $this->validate($request, 
        [
            'departureDate' => 'required|date|after:now',
            'returnDate'    => 'required|date_format:"Y-m-d"|after:' . $after_date . '|before:' . $max_days
        ], 
        [
            'departureDate.after' => 'Your departure date should be tomorrow or any date in the future',
            'returnDate.after'    => 'Your return date should be 3 or more days after the departure date',
            'returnDate.before'   => 'Your return date should be no more than 180 days from the departure date',
        ]
    );
};

我假设您在某个地方定义了LeaveDate,因此您正在使用$this->departureDate,但是如果它是来自您的请求,则应将其更改为$request->departureDate