-
Notifications
You must be signed in to change notification settings - Fork 11k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[8.x] Add Validator::excludeArrays() to exclude array keys that aren't included in the validation rules #37943
Conversation
This behavior of the validator has caused me trouble in the past too. The |
@SjorsO that's the plan for Laravel 9. But since it's a breaking change, people must opt-in. |
foreach ($this->getRules() as $key => $rules) { | ||
if ($this->excludeArrays && | ||
in_array('array', $rules) && | ||
! empty(preg_grep('/^'.$key.'\.*/', array_keys($this->implicitAttributes)))) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Escaping the regex pattern with preg_quote($key, '/')
may be required to cover every character that <input name="">
allows, not just restricted to alphanumeric/underscore.
e.g., validating a parsed XML document (external spec) can lead to some weird field name edge cases with hyphens, slashes, etc.
If anyone has good ideas for the final method name of this method let me know... /cc @derekmd |
So in Laravel 9 we won't have to call
It isn't easy to name something that fixes such a specific problem. Maybe something like:
|
|
I ran into this issue a little over a month ago too, but as I was working on a fix I found the (at the time undocumented) feature that you could add the keys behind the array rule, like Of course, validating the absence of invalid keys is not the same as not returning them in the validated() method if they don't have a rule. One additional feature I made in my fix was allowing |
@bonroyage I forgot you can do that... 👀 |
I've run into this a few times as well. Nice work, Mohamed!
|
|
And it gets even trickier with more levels of nesting, like I'm not sure if the current approach offers a way to restrict keys for both arrays |
Until Laravel 9 you can make this the default using: app()->resolving(
\Illuminate\Validation\Factory::class,
fn($factory) => $factory->excludeUnvalidatedArrayKeys()
); |
Given the following rules:
The validator will return the
users
attribute with all its children:You can see that the
job
key was returned even though it wasn't included in the validator rules.This PR adds a new
Validator::excludeArrays()
that when added to aboot
method of a service provider, will instruct the validator to exclude any array keys that weren't validated: