6

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.

0

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

these fields are not mandatory, but shouldn't be empty if exist in input request.
@user947668 Is the array itself allowed to be empty? With 'branches.*' => 'required|max:255' I'm checking if the fields are empty for each row of the array here.
@user947668 else use filled instead
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.