Skip to content

Commit 2671445

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

2 files changed

Lines changed: 33 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 (null === $nowFieldVaule) {
446+
return false;
447+
}
441448
}
442449
}
443450

tests/system/Validation/ValidationTest.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1854,6 +1854,28 @@ 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+
18571879
/**
18581880
* @see https://github.com/codeigniter4/CodeIgniter4/issues/8128
18591881
*/

0 commit comments

Comments
 (0)