Laravel 5.3 date validator: equal to or after start_date

前端 未结 4 1531
不思量自难忘°
不思量自难忘° 2020-12-29 19:04

I\'m using Laravel 5.3 to validate start_date and end_date for an event. end_date should be equal to start_date or the after date. end_date >= start_date

4条回答
  •  无人及你
    2020-12-29 19:44

    Be careful when you set a validation rule after_or_equal:now and date_format with a format without hours, minutes or seconds!

    For example:

    $validationRules = [
        'my_time_start' => [
            'date_format:Y-m-d',// format without hours, minutes and seconds.
            'after_or_equal:now'
        ]
    ];
    

    Laravel passing all date fields into the strtotime() function. Including now string. And strtotime('now') will return a unix timestamp with current minutes, hours and seconds.

    For example, the today date is 2020-05-03. When you send a date value 2020-05-03 into your script, Laravel will pass 2 values into the strtotime() for compare:

    strtotime('2020-05-03'); // always 1588489200
    strtotime('now'); // NOT PREVIOUS VALUE, a different value each second, timestamp including current minutes, hour and seconds.
    

    And you will always fail a validation (exclude a 1 second of the day).

    To fix it, you should use:

    $validationRules = [
        'my_time_start' => [
            'date_format:Y-m-d',// format without hours, minutes and seconds.
            'after_or_equal:' . date('Y-m-d'), // not 'now' string
        ]
    ];
    

提交回复
热议问题