Laravel 5.2+ date before and after date validation not working

11,993

Solution 1

In the laravel docs for 5.3 (the version I tested):

Instead of passing a date string to be evaluated by strtotime, you may specify another field to compare against the date:

'finish_date' => 'required|date|after:start_date'

https://laravel.com/docs/5.3/validation#rule-after

The string following the "after" rule (start_date in this case) is not a database field, but part of the input string passed to your validator.

So, following what you were attempting to do above, the validator was expecting a field named "created_at" to be passed along with the rest of your submitted input, which likely didn't exist since your intent was to have it read from your model, which would cause it to fail.

Long story short, your last statement was correct. The "before/after" rules do not reference model fields, but rather other input fields passed to the validator, OR date strings that can be interpreted by "strtotime"

Solution 2

This can be validated as:

'expected_at'  => 'required|before:' . date('Y-m-d') . '|date_format:Y-m-d',

You can even pass validator a date argument and compare at the time of validation. I assume, you are searching for date_format validator.

Solution 3

Agree with @Gordon, and you can try this, without format in FormRequest:

'expected_at' => "date|after:{$this->user()->created_at}",

Note: The reason of non-ability to refer to DB value is because no defined model to use in this stage.

Share:
11,993
Matthew Malone
Author by

Matthew Malone

Mechanical Engineer by education and career. Now I am attempting to become a better coder!

Updated on June 18, 2022

Comments

  • Matthew Malone
    Matthew Malone almost 2 years

    This works

    'expected_at' => 'date|after:"2016-04-09 10:48:11"',
    

    And this works

    $rules['expected_at'] = 'date|after:'.$opportunity->created_at;
    

    This does not work

    'expected_at' => 'date|after:created_at',
    

    The "created_at" value in the database is exactly the following

    2016-04-09 10:48:11
    

    Note the form is passing the expected_at date to the validator in the following format

    2016-04-09
    

    I assume that this means you cannot directly reference a model field in a validator?

  • Matthew Malone
    Matthew Malone about 8 years
    No this is not what I am asking, the date format translates fine. The problem is Laravel cannot reference a field in the model using the validator syntax - you have to have it as $opportunity->created_at;