0

I have a form that submits an array named prazos, and I want to make sure each item is a valid datetime or null. Following the answers to this question and the Laravel docs, I have this in my Controller:

use Illuminate\Support\Facades\Validator;

// ...

$rules = array([
            'prazos' => 'required|array',
            'prazos.*' => 'nullable|date'
           ]);

$validator = Validator::make($request->all(), $rules);
$data = $validator->valid()['prazos'];
foreach($data as $id => $prazo) {
    // use $data to update my database
    // ...
}

The issue is, the validator is not actually stopping invalid content. If I try to submit "loldasxyz" or other gibberish, I get an error from the database. What am I doing wrong?

Note: previously I had been using validators with the syntax $data = $request->validate($rules), but for some reason it didn't work for the array-type data ($data came back empty). I'm not sure if there is some difference in how those different methods work.

Edit: this is what the parameter bag in $request looks like when I test it (the indices are ids, which is why they start at 1):

    #parameters: array:3 [▼
      "_token" => "Rf6mAp4lqhpZzQRxaxYsees1M0NfrFKpbGe4Hy28"
      "_method" => "PUT"
      "prazos" => array:5 [▼
        1 => "2021-03-22 21:21"
        2 => "2021-03-03 11:27"
        3 => "jhbkjhg"
        4 => null
        5 => "2021-03-02 14:21"
      ]
    ]

And this is what the validated $data comes out as:

array:5 [▼
  1 => "2021-03-22 21:21"
  2 => "2021-03-03 11:27"
  3 => "jhbkjhg"
  4 => null
  5 => "2021-03-02 14:21"
]

I wish it would tell me the third value is invalid.

MOzSalles
  • 195
  • 8
  • dd your request and see if its coming as `prazos[0], prazos[1] `or your input are coming in some other format, and I think you should `nullable` instead of `sometimes` – Zohaib Mar 03 '21 at 08:12
  • 1
    you're right, since there are no missing values, just null ones... done. – MOzSalles Mar 03 '21 at 14:43

1 Answers1

0

Heres what youre looking for: https://laravel.com/docs/8.x/validation#rule-date-equals

The field under validation must be equal to the given date. The dates will be passed into the PHP strtotime function in order to be converted into a valid DateTime instance.