I have a form with a series of numbers in an array:
<input type="number" name="items[{{ $sku }}]" min="0" />
<input type="number" name="items[{{ $sku }}]" min="0" />
<input type="number" name="items[{{ $sku }}]" min="0" />
I would like to validate that there is at least one of those input fields that has a value.
I tried the following in my OrderCreateRequest, yet the test is passing:
return [
'items' => 'required|array|min:1'
];
Am I missing something?
you can call validate() method directly on Request object like so: $data = $request->validate([ "name" => "required|array|min:3", "name. *" => "required|string|distinct|min:3", ]); Hope it helps!!
If you added more then one validation on your field like required, integer, min and max then if first is fail then other should stop to display error message. right now by default it print other too. so you can prevent that by using bail validation rule in laravel.
Laravel Form Request class comes with two default methods auth() and rules() . You can perform any authorization logic in auth() method whether the current user is allowed to request or not. And in rules() method you can write all your validation rule.
I think you need a custom validation rule like the following because min is not for the elements of the array.
Validator::extend('check_array', function ($attribute, $value, $parameters, $validator) {
return count(array_filter($value, function($var) use ($parameters) { return ( $var && $var >= $parameters[0]); }));
});
You can create ValidatorServiceProvider and you can add these lines to boot method of ValidatorServiceProvider. Then you need to add Provider to your providers array in config/app.php.
App\Providers\ValidatorServiceProvider::class,
Or you just add them top of the action of your controller.
At the end you can use it like this in your validation rules.
'items' => 'check_array:1',
Note: if I understand you correctly it works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With