Laravel 4 validation constant pass - php

I'm using Laravel 4.2.8 and trying to validate the next form:
The first select field is required. And only one is required from the next three fields.
Phone with formatting is the last. And another two are for digits (some IDs).
I validate in controller, the code is next:
public function getApplication()
{
$input = Input::except('_token');
Debugbar::info($input);
$input['phone'] = preg_replace('/[^0-9]/', '', $input['phone']); // remove format from phone
$input = array_map('intval', $input); // convert all numeric data to int
Debugbar::info($input);
$rules = [ // Validation rules
['operation-location' => 'required|numeric'],
['app-id' => 'numeric|min:1|required_without_all:card-id,phone'],
['card-id' => 'numeric|digits:16|required_without_all:app-id,phone'],
['phone' => 'numeric|digits:12|required_without_all:app-id,card-id']
];
$validator = Validator::make($input, $rules);
if ($validator->passes()) {
Debugbar::info('Validation OK');
return Redirect::route('appl.journal', ['by' => 'application']);
}
else { // Validation FAIL
Debugbar::info('Validation error');
// Redirect to form with error
return Redirect::route('appl.journal', ['by' => 'application'])
->withErrors($validator)
->withInput();
}
}
As you may see I convert numeric IDs to integers myself and leave only number for phone number.
The problem is when I submit form as it is, it passes validation, despite one field is required and starter phone format is too short.
I've tried changing required_without_all to just required on all fields (!), but it still passes fine with blank empty form submitted.
And I expect at least one field to be properly filled.
Debug of my inputs.
Initial:
array(4) [
'operation-location' => string (1) "0"
'app-id' => string (0) ""
'card-id' => string (0) ""
'phone' => string (6) "+3 8(0"
]
After conversion to int:
array(4) [
'operation-location' => integer 0
'app-id' => integer 0
'card-id' => integer 0
'phone' => integer 380
]
Posted similar smaller problem to Laravel issues.

I know this sounds weird but I think this is just an issue with your rules array.
You current rules array is an array of arrays. The Validator looks for an array with keys and values. I believe your current rules are being parsed as keys, but with no value. And then the Validator was basically seeing no rules, and it automatically passed. Try this.
$rules = [
'operation-location' => 'required|numeric',
'app-id' => 'numeric|min:1|required_without_all:card-id,phone',
'card-id' => 'numeric|digits:16|required_without_all:app-id,phone',
'phone' => 'numeric|digits:12|required_without_all:app-id,card-id'
];

Related

Laravel validate array element is required if array is present

Laravel 5.7. I have a form request validation for a model Foo. The model has an optional field bar, which must be an array. If it is present, it must contain two keys, bing and bang. But if the array is absent, obviously these two keys should not be validated.
This is what I have so far:
return [
'bar' => 'bail|array|size:2',
'bar.bing' => 'required|numeric',
'bar.bang' => 'required|numeric',
];
This works when I send a request with the bar array present. But when I send a request without the bar array, I still get the validation errors
The bar.bing field is required
The bar.bang field is required
How can I make them only required when bar is present?
Try with this rules
return [
'bar' => 'nullable|bail|array|size:2',
'bar.bing' => 'required_with:bar|numeric',
'bar.bang' => 'required_with:bar|numeric',
]
Docs for required_with
Here's what I tend to do in this sort of situations
public function rules(): array
{
$rules = [
// ...
];
if ($this->bar) {
$rules['bar'] = 'array|size:2';
$rules['bar.bing'] = 'required|numeric';
$rules['bar.bang'] = 'required|numeric';
}
return $rules;
}

Validate array of inputs in form in Laravel 5.7

My form has the same input field multiple times. My form field is as follows:
<input type='text' name='items[]'>
<input type='text' name='items[]'>
<input type='text' name='items[]'>
And request contains ($request['items'):
array:1 [▼
"items" => array:3 [▼
0 => "item one"
1 => "item two"
2 => "item three"
]
]
I want atleast one of the items to be filled. My current validation in the controller is
$validator = Validator::make($request->all(),[
'items.*' => 'required|array|size:1'
]);
It does not work. I tried with combination of size, required, nullable. Nothing works.
In fact, it's enough to use:
$validator = Validator::make($request->all(),[
'items' => 'required|array'
]);
The changes made:
use items instead of items.* - you want to set rule of general items, if you use items.* it means you apply rule to each sent element of array separately
removed size:1 because it would mean you want to have exactly one element sent (and you want at least one). You don't need it at all because you have required rule. You can read documentation for required rule and you can read in there that empty array would case that required rule will fail, so this required rule for array makes that array should have at least 1 element, so you don't need min:1 or size:1 at all
You can check it like this:
$validator = Validator::make($request->all(), [
"items" => "required|array|min:1",
"items.*" => "required|string|distinct|min:1",
]);
In the example above:
"items" must be an array with at least 1 elements.
Values in the "items" array must be distinct (unique) strings, at least 1 characters long.
You can use a custom rule with a closure.
https://laravel.com/docs/5.7/validation#custom-validation-rules
To check if an array has all null values check it with array_filter which returns false if they're all null.
So something like...
$request->validate([
'items' => [
// $attribute = 'items', $value = items array, $fail = error message as string
function($attribute, $value, $fail) {
if (!array_filter($value)) {
$fail($attribute.' is empty.');
}
},
]
]);
This will set the error message: 'items is empty."
Knowing you are using the latest version of Laravel, I really suggest looking into Form Request feature. That way you can decouple validation from your controller keeping it much cleaner.
Anyways as the answer above me suggested, it should be sufficient for you to go with:
'items' => 'required|array'
Just Do it normally as you always do:
$validator = Validator::make($request->all(),[
'items' => 'required'
]);
You should try this:
$validator = $request->validate([
"items" => "required|array|min:3",
"items.*" => "required|string|distinct|min:3",
]);

validate array or an array of integers in Laravel

I have a input request that can be an integer or an array of integer values.
How can I check validation of that in Laravel? I'm using Laravel 5.5.I know that there is a simple array validation rules that checks an input is an array or not:
array
The field under validation must be a PHP array.
Is there any predefined validation rule or should I write a new one? if yes, How?
$input = $request->all();
//Check if input param is an array
if(is_array($input['item']))
{
//Array validator
$Validator = Validator::make($input,
[
'item' => 'required', //Array with key 'item' must exist
'item.*' => 'sometimes|integer', //All values should be integers
]);
}
else
{
//Integer validator
$Validator = Validator::make($input,
[
'item' => 'required|integer',
]);
}
Use sometimes it applies validation rule only if that input parameter exist. Hope this helps

Laravel filled validation rule for array element

I need to check input array of strings and raise warning if at least one of array elements is empty.
The following rule is used:
return Validator::make($data, [
'branches' => 'array',
'branches.*' => 'filled|max:255'
]);
However it seems filled rule doesn't work (while min:1 works fine).
Should it work with array elements or not?
UPDATE:
branches array is not mandatory, but if exists it should contain non empty elements.
UPDATE:
Finally found mistake in my validation rule.
It should look like
return Validator::make($data, [
'branches' => 'array',
'branches.*.*' => 'filled|max:255'
]);
since input array is array of arrays. Now filled rule works as expected with my input data.
Use required instead
return Validator::make($data, [
'branches' => 'required|array',
'branches.*' => 'required|max:255'
]);
From the documentation: https://laravel.com/docs/5.5/validation#available-validation-rules
required
The field under validation must be present in the input data and not
empty. A field is considered "empty" if one of the following
conditions are true:
The value is null.
The value is an empty string.
The value is an empty array or empty Countable object.
The value is an uploaded file with no path.
If you want to validate the array only if there is field data present use filled. You can combine this with present.
return Validator::make($data, [
'branches' => 'present|array',
'branches.*' => 'filled|max:255'
]);
filled
The field under validation must not be empty when it is present.
present
The field under validation must be present in the input data but can be empty.
Considering your comment you should try nullable
return Validator::make($data, [
'branches' => 'nullable|array',
'branches.*' => 'nullable|max:255'
]);
OR
You can use presentthis will ensure that array should be passed either with values or just an empty array
return Validator::make($data, [
'branches' => 'present|array',
'branches.*' => 'nullable|max:255'
]);

Validate value 0 and range based validation in Lumen

I want to perform following validation on my textfield using Lumen Validation:
The value must be greater than 0 and less than or equal to 100
My current code is:
$validator = Validator::make($params, [
'weight' => 'required'
]);
if ($validator->fails()) {
$messages = $validator->errors();
$message = $messages->first();
return $message;
exit;
}
You can use the between validation rule to check this. The parameters are inclusive.
You also need to add in the numeric validation rule so that between will know to check if the numeric value is between the supplied values. Without the numeric validation, it would validate the length of the string, not the numeric value of it.
$validator = Validator::make($params, [
'weight' => 'required|numeric|between:1,100'
]);

Categories