Validator/data_get on the root of an indexed array #61210
Replies: 2 comments 5 replies
|
There isn't an attribute name that refers to the root, and the reason is structural rather than an oversight — rules are keyed by attribute, so a rule only exists by virtue of having a name to hang off. The root has no name. The obvious thing to reach for is $pattern = str_replace('\*', '[^\.]*', preg_quote($attribute, '/'));
$data = ValidationData::initializeAndGatherData($attribute, $this->data);
foreach ($data as $key => $value) {
if (Str::startsWith($key, $attribute) || (bool) preg_match('/^'.$pattern.'\z/', $key)) {With Which leaves wrapping, and honestly it's fine: $validator = Validator::make(['items' => $data], [
'items' => [
'array',
new RestrictedDomain('domain'),
],
'items.*.domain' => ['string'],
]);Your rule's contract doesn't change at all — it still receives the same array it did in your working example, so nothing about Worth knowing |
|
There's no built-in way to do this, because validation rules are keyed by field path, and there's no path that represents "the root itself" — that's exactly why your Practical fix: wrap the input under a synthetic key before validating: $data = Validator::make(['root' => $data], [
'root' => ['array', new RestrictedDomain('domain')],
'root.*.domain' => ['string'],
]);That gives you the same "access the whole array" behavior your |
Uh oh!
There was an error while loading. Please reload this page.
This works perfectly fine:
But there are some cases where I have something like this, I was wondering if there was a way to select the whole array just like 'items' items does.
In this example the custom rule would only get access too.
All reactions