Skip to content

Commit

Permalink
Merge pull request #6243 from iRedds/fix/validation-leading-asterisk
Browse files Browse the repository at this point in the history
Fix: Validation of fields with a leading asterisk.
  • Loading branch information
kenjis authored Jul 9, 2022
2 parents ba7d36c + 770d5a1 commit bc688d9
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 2 deletions.
6 changes: 4 additions & 2 deletions system/Validation/Validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,9 @@ public function run(?array $data = null, ?string $group = null, ?string $dbGroup

if (strpos($field, '*') !== false) {
$values = array_filter(array_flatten_with_dots($data), static fn ($key) => preg_match(
'/^' . str_replace('\.\*', '\..+', preg_quote($field, '/')) . '$/',
'/^'
. str_replace(['\.\*', '\*\.'], ['\..+', '.+\.'], preg_quote($field, '/'))
. '$/',
$key
), ARRAY_FILTER_USE_KEY);
// if keys not found
Expand Down Expand Up @@ -657,7 +659,7 @@ public function getError(?string $field = null): string
}

$errors = array_filter($this->getErrors(), static fn ($key) => preg_match(
'/^' . str_replace('\.\*', '\..+', preg_quote($field, '/')) . '$/',
'/^' . str_replace(['\.\*', '\*\.'], ['\..+', '.+\.'], preg_quote($field, '/')) . '$/',
$key
), ARRAY_FILTER_USE_KEY);

Expand Down
19 changes: 19 additions & 0 deletions tests/system/Validation/ValidationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1131,6 +1131,12 @@ public function validationArrayDataCaseProvider(): iterable
['foo' => ['boz']],
]],
];

yield 'leading-asterisk' => [
true,
['*.foo' => 'required'],
[['foo' => 'bar']],
];
}

/**
Expand Down Expand Up @@ -1357,4 +1363,17 @@ public function testNestedArrayThrowsException(): void
'beneficiaries_accounts.account_2.purpose' => 'The PURPOSE field must be at least 3 characters in length.',
], $this->validation->getErrors());
}

public function testRuleWithLeadingAsterisk(): void
{
$data = [
['foo' => 1],
['foo' => null],
];

$this->validation->setRules(['*.foo' => 'required'], ['1.foo' => ['required' => 'Required {field}']]);

$this->assertFalse($this->validation->run($data));
$this->assertSame('Required *.foo', $this->validation->getError('*.foo'));
}
}
1 change: 1 addition & 0 deletions user_guide_src/source/changelogs/v4.2.2.rst
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ Changes
*******

- Fixed: ``BaseBuilder::increment()`` and ``BaseBuilder::decrement()`` do not reset the ``BaseBuilder`` state after a query.
- Fixed: Validation of fields with a leading asterisk (wildcard).
- Now ``CLIRequest::isCLI()`` always returns true.
- Now ``IncommingRequest::isCLI()`` always returns false.

Expand Down

0 comments on commit bc688d9

Please sign in to comment.