Laravel filled validation rule for array element - php

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'
]);

Related

Laravel validate array and exclude on specific array value

I have an array of values that I send together with other fields in a form to laravel.
The array contains a role_id field and a status field, the status can be I (Insert) U (update) D (Delete). When I validate the values in the array I want it to skip the ones where the status equals D. Otherwise I want it to validate.
private function checkValuesUpdate($userid = null)
{
return Request::validate(
[
'displayname' => 'required',
'username' => 'required',
'email' => ['nullable', 'unique:contacts,email' . (is_null($userid ) ? '' : (',' . $userid ))],
'roles.*.role_id' => ['exclude_if:roles.*.status,D', 'required']
]
);
}
I can't seem to get it to work. I've been searching all over the place for functional code as well as the Laravel documentation. But no luck so far. Has anybody ever done this?
Your problem comes from a misunderstanding of the exclude_if rule. It doesn't exclude the value from validation, it only excludes the value from the returned data. So it would not be included if you ran request()->validated() to get the validated input values.
According to the documentation, you can use validation rules with array/star notation so using the required_unless rule might be a better approach. (Note there's also more concise code to replace the old unique rule, and I've added a rule to check contents of the role status.)
$rules = [
'displayname' => 'required',
'username' => 'required',
'email' => [
'nullable',
Rule::unique("contacts")->ignore($userid ?? 0)
],
'roles' => 'array',
'roles.*.status' => 'in:I,U,D',
'roles.*.role_id' => ['required_unless:roles.*.status,D']
];

Using excludes_unless validation rule with arrays in Laravel

Laravel's exclude_unless,field,value rule doesn't seem to work in the instance where field is an array of values and value is contained within the field array.
Given the following:
$validator = Validator::make($request->all(), [
'some_array' => 'array',
'some_field' => 'exclude_unless:some_array,foo|alpha_num',
]);
Where some_array is equal to ['foo'], the validator will fail to exclude some_field. This seems to be because the comparison that lies beneath excludes_unless is in_array(['foo'], ['foo']) which returns false.
Is it possible to achieve the same logic of exclude_unless — excluding a field from validation if another field equals a certain value, but where the field being compared against is an array and we're checking that the value is in that array?
As long as you're using Laravel 8.55 or above, you could use Rule::when():
use Illuminate\Validation\Rule;
$someArray = $request->input('some_array', []);
$validator = Validator::make($request->all(), [
'some_array' => 'array',
'some_field' => Rule::when(!empty(array_intersect(['foo'], $someArray)), ['exclude']),
]);

Laravel Validation rules: required_without

I have two fields: Email and Telephone
i want to create a validation where one of two fields are required and if one or both fields are set, it should be the correct Format.
I tried this, but it doesnt work, i need both though
public static array $createValidationRules = [
'email' => 'required_without:telephone|email:rfc',
'telephone' => 'required_without:email|numeric|regex:/^\d{5,15}$/',
];
It is correct that both fields produce the required_without error message if both are empty. This error message clearly says that the field must be filled if the other is not. You may change the message if needed:
$messages = [
'email.required_without' => 'foo',
'telephone.required_without' => 'bar',
];
However, you must add the nullable rule, so the format rules don't apply when the field is empty:
$rules = [
'email' => ['required_without:telephone', 'nullable', 'email:rfc'],
'telephone' => ['required_without:email', 'nullable', 'numeric', 'regex:/^\d{5,15}$/'],
];
Furthermore: It is recommended writing the rules as array, especially when using regex.

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 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

Categories