Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

RonanH's avatar

Validate Array with unknown key's

Hi,

I want to validate the values sent from a form that contains an undetermined amount of checkboxes.

These send an array of deploymentCustomers[] to the Request. I can validate that deploymentCustomers[] is an array but i don't know how i can validate each value in the array as i don't know what the array keys will be.

return request()->validate([ 'name' => ['required', 'string', 'max:255'], 'deploymentCustomers' => ['array'] ]);

Any ideas on how to do this?

0 likes
4 replies
tykus's avatar

If you don't know what the keys are, then what validation can you realistically perform?

Snapey's avatar

name the form elements appropriately.

For instance, fields named name="customer[]name" and name="customer[]email"

can be validated in the back-end as

$rules = [
	'customer.*.name' => 'required|max:50',
	'customer.*.email' => 'required|email:rfc|max:100',
]

for example

RonanH's avatar

I'm not sure if i'm missing something but as i don't know what the key names will be i don't see how the dot notation will allow me to do it. I have created a function for creating rules for the unknown array keys.

public function validateDeployment() { $rules = $this->validateDeploymentRules(); return request()->validate($rules); }

public function validateDeploymentRules()
{
    $rules = [
        'name' => ['required', 'string', 'max:255']
    ];

    // Add rules for all the Add Customer checkboxes
    $deploymentCustomers = request()->input('deploymentCustomers');
    foreach ($deploymentCustomers as $index => $value){
        $rules['deploymentCustomers.' . $index] = ['integer'];
    }
    return $rules;
}

Please or to participate in this conversation.