#Array validation message for unspecified keys

1 messages · Page 1 of 1 (latest)

crude sentinel
#

Hi Laravel-ers,

I am doing FormRequest validation. I am using the array rule (https://laravel.com/docs/10.x/validation#rule-array) to ensure that only specified keys are allowed in the validated array. For example:

$rules = [
  'example' => ['array:something,another'],
];

However, if this rule encounters an array key that isn't in that whitelist the error message I get isn't very descriptive:

The :attribute field must be an array. (https://github.com/laravel/framework/blob/10.x/src/Illuminate/Translation/lang/en/validation.php#L24)

This message doesn't reference the incorrect array key at all, making it hard for the end user to work out what they did wrong.

Can I improve this error message such that it highlights the fact that an incorrect key has been passed?

I would have thought that this has been asked before but my Google-fu clearly isn't strong today!

Thanks for your help,
Ari

runic meadow
crude sentinel
#

Thanks, so you're suggesting I alter the message to say something like The :attribute field must be an array with keys 'something' and/or 'another'.? This would require me to hardcode the valid keys in the message, I presume?

Is there instead any way I can access the specific key that has caused the validation to fail and return a message like The :key key is not valid for the :attribute field.? That would be much more flexibile!

runic meadow
#

Nothing like that is in the docs so you'd have to check the source code

crude sentinel
#

Okay, thanks for your help. I'll leave this as unsolved for the time being as you've given me a nice workaround, but not a solution as such!

runic meadow
crude sentinel
#

Thanks again Cole, unfortunately that section just addresses validating fields within arrays (including the useful :index and :position placeholders), but this doesn't apply for the array rule that controls the suitable keys.

worthy hatch
#

You could use this I think

$rules = [
  'example' => ['array'],
  'example.something' => ['required'],
  'example.another' => ['required'],
]

Along with this, in for example a service provider (https://github.com/laravel/framework/pull/37943)

Validator::excludeUnvalidatedArrayKeys();

That way it won't throw an error if too many keys are posted, but it'll just discard them

crude sentinel
#

Thanks Robert! I've been thinking about whether I can use a rule on the nested keys themselves rather than the array, but the problem is that they're not actually required keys in the array (just whitelisted). So I don't want the rule to fail if the keys aren't present in the array, just if there are keys that aren't in the whitelist in the array. 🤔