Skip to content

Commit 28f605b

Browse files
committed
fix(Validation): correct required_without logic and prevent array key warnings
1 parent b08160c commit 28f605b

2 files changed

Lines changed: 56 additions & 4 deletions

File tree

‎system/Validation/Rules.php‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -429,15 +429,22 @@ public function required_without(
429429

430430
$fieldData = dot_array_search($otherField, $data);
431431
$fieldSplitArray = explode('.', $field);
432-
$fieldKey = $fieldSplitArray[1];
432+
$fieldKey = $fieldSplitArray[1] ?? null;
433433

434434
if (is_array($fieldData)) {
435-
return ! empty(dot_array_search($otherField, $data)[$fieldKey]);
435+
if (empty($fieldData[$fieldKey])) {
436+
return false;
437+
}
438+
439+
continue;
436440
}
437-
$nowField = str_replace('*', $fieldKey, $otherField);
441+
442+
$nowField = str_replace('*', (string) $fieldKey, $otherField);
438443
$nowFieldVaule = dot_array_search($nowField, $data);
439444

440-
return null !== $nowFieldVaule;
445+
if ($nowFieldVaule === null) {
446+
return false;
447+
}
441448
}
442449
}
443450

‎tests/system/Validation/ValidationTest.php‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1854,6 +1854,51 @@ public function testRequireWithoutWithAsterisk(): void
18541854
);
18551855
}
18561856

1857+
/**
1858+
* Test that `required_without` checks all fields in dot-notation when there are multiple fields.
1859+
*/
1860+
public function testRequireWithoutMultipleWithAsterisk(): void
1861+
{
1862+
$data = [
1863+
'a' => [
1864+
['b' => 1, 'c' => 2, 'd' => ''],
1865+
['b' => 1, 'c' => '', 'd' => ''],
1866+
],
1867+
];
1868+
1869+
$this->validation->setRules([
1870+
'a.*.d' => 'required_without[a.*.b,a.*.c]',
1871+
])->run($data);
1872+
1873+
$this->assertSame(
1874+
'The a.*.d field is required when a.*.b,a.*.c is not present.',
1875+
$this->validation->getError('a.1.d'),
1876+
);
1877+
}
1878+
1879+
/**
1880+
* Test that `required_without` handles a non-asterisk field checked against an asterisk field
1881+
* without throwing undefined array key warnings for `$fieldSplitArray[1]`.
1882+
*/
1883+
public function testRequireWithoutAsteriskOnNonAsteriskField(): void
1884+
{
1885+
$data = [
1886+
'foo' => '',
1887+
'a' => [
1888+
['b' => ''],
1889+
],
1890+
];
1891+
1892+
$this->validation->setRules([
1893+
'foo' => 'required_without[a.*.b]',
1894+
])->run($data);
1895+
1896+
$this->assertSame(
1897+
'The foo field is required when a.*.b is not present.',
1898+
$this->validation->getError('foo'),
1899+
);
1900+
}
1901+
18571902
/**
18581903
* @see https://github.com/codeigniter4/CodeIgniter4/issues/8128
18591904
*/

0 commit comments

Comments
 (0)