Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.2+ date before and after date validation not working

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?

like image 259
Matthew Malone Avatar asked Feb 08 '23 07:02

Matthew Malone


2 Answers

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"

like image 147
Gordon Richard Peach Avatar answered Feb 10 '23 06:02

Gordon Richard Peach


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.

like image 35
tnchalise Avatar answered Feb 10 '23 05:02

tnchalise