Back

Validate dates before saving


Weyler Antonio Uicab Pat posted 8 months ago

I would like to validate two dates that come from my form, $start and $end, in such a way that the difference between $start and $end is equal to 6 (they are weekly periods starting from Monday and ending on Sunday), then also $end can not be less than $start.


Correct, there is a difference of 6 days

$start = 2018-10-01 //01 Octuber 2018
$end   = 2018-10-07 //07 Octuber 2018

Incorrect, $start and $end they are equal

$start = 2018-10-01  //01 Octuber 2018
$end   = 2018-10-01 //01 Octuber 2018

Incorrect, $end is less than $start
 
$start = 2018-10-01    //01 Octuber 2018
$end   = 2018-09-30 //30 September 2018

Incorrect, there is a difference of 1 day

$start = 2018-09-30 //01 Octuber 2018
$end   = 2018-10-01 //30 September 2018


Incorrect, there is a difference of 4 days

$start = 2018-10-01   //01 Octuber 2018
$end   = 2018-10-05 //05 Octuber 2018

How could I create a validation rule for the dates? Would the validation be in the model or in the validation rules of the controller?

First of all, Thanks. Regards

Haryo Adi replied 8 months ago

there's several ways to do this. Here I pick one that I think the fastest to write.

assuming the dates key name is start and end in the form, then in your controller:

<?php

namespace App\Http\Controllers;

use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
...

//your controller
class Controller extends BaseController
{
    use ValidatesRequests;


    //your controller function
    public function doSomething(Request $request){

        //create custom - Closure rule
        $sixDayAfter = function ($attribute, $value, $fail) use ($request) {

            //create Carbon instance of actual & expected end date
            $actualEndDate = Carbon::make($value);
            $expectedEndDate = Carbon::make($request->start)->addDays(6);

            //compare the dates. if they're different, validation fails
            if ( ! $actualEndDate->isSameDay($expectedEndDate)) {
                
                $fail('the end date should be 6 days after the start date ');
                //or whatever error message you want
            }
        };

        //do the validation
        $this->validate($request, [
            'start' => 'required',
            'end' => $sixDayAfter
        ]);

        //the dates ok, continue...
        ...
    }
}

further reference:

Hope it helps


Sign in to participate in this thread!



We'd like to thank these amazing companies for supporting us