I have an array of integer like this $someVar = array(1,2,3,4,5)
. I need to validate $someVar
to make sure every element is numeric.How can I do that?
I know that for the case of a single valued variable, the validation rule would be something like this $rules = array('someVar'=>'required|numeric')
. How can I apply the same rule to every element of the array $someVar
?
Thanks a lot for helping.
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", ]);
For more complex validation scenarios, you may wish to create a “form request.” Form requests are the custom request classes that contain validation logic. To create a form request class, use the make: request Artisan CLI command. It will create a file inside the app >> Http >> Requests folder called FieldRequest.
By default, Laravel 'confirmed' validator adds the error message to the original field and not to the field which usually contains the confirmed value.
Now laravel has option to set condition on array elements. No need to write your own validator for simple things like validation int array. Use this (if using in controller)-
$validator = \Validator::make(compact('someVar'), [ 'someVar' => 'required|array', 'someVar.*' => 'integer' ]); $this->validateWith($validator);
or
$this->validate($request, [ 'someVar' => 'array', 'someVar.*' => 'int' ]);
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