From 8d309738037cc0d69ae82cce8e4fca0a3771e9db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Najdanovic=CC=81=20Ivan?= Date: Fri, 8 May 2020 14:35:19 +0200 Subject: [PATCH] Validation - Handle 'required_with' and 'required_without' on 'permit_empty' --- system/Validation/Validation.php | 33 ++++++++++++++- tests/system/Validation/RulesTest.php | 60 +++++++++++++++++++++++++++ 2 files changed, 92 insertions(+), 1 deletion(-) diff --git a/system/Validation/Validation.php b/system/Validation/Validation.php index e42560834017..00668b1ed4a3 100644 --- a/system/Validation/Validation.php +++ b/system/Validation/Validation.php @@ -250,7 +250,38 @@ protected function processRules(string $field, string $label = null, $value, $ru { if (! in_array('required', $rules) && (is_array($value) ? empty($value) : (trim($value) === ''))) { - return true; + $passed = true; + + foreach ($rules as $rule) + { + if (preg_match('/(.*?)\[(.*)\]/', $rule, $match)) + { + $rule = $match[1]; + $param = $match[2]; + + if (! in_array($rule, ['required_with', 'required_without'])) + { + continue; + } + + // Check in our rulesets + foreach ($this->ruleSetInstances as $set) + { + if (! method_exists($set, $rule)) + { + continue; + } + + $passed = $passed && $set->$rule($value, $param, $data); + break; + } + } + } + + if ($passed === true) + { + return true; + } } $rules = array_diff($rules, ['permit_empty']); diff --git a/tests/system/Validation/RulesTest.php b/tests/system/Validation/RulesTest.php index 4e0077f3a632..03427643886c 100644 --- a/tests/system/Validation/RulesTest.php +++ b/tests/system/Validation/RulesTest.php @@ -284,6 +284,66 @@ public function emptysProvider() ['foo' => 0.0], true, ], + [ + ['foo' => 'permit_empty|required_with[bar]'], + ['foo' => ''], + true, + ], + [ + ['foo' => 'permit_empty|required_with[bar]'], + ['foo' => 0], + true, + ], + [ + [ + 'foo' => 'permit_empty|required_with[bar]', + ], + [ + 'foo' => 0.0, + 'bar' => 1, + ], + true, + ], + [ + [ + 'foo' => 'permit_empty|required_with[bar]', + ], + [ + 'foo' => '', + 'bar' => 1, + ], + false, + ], + [ + ['foo' => 'permit_empty|required_without[bar]'], + ['foo' => ''], + false, + ], + [ + ['foo' => 'permit_empty|required_without[bar]'], + ['foo' => 0], + true, + ], + [ + [ + 'foo' => 'permit_empty|required_without[bar]', + ], + [ + 'foo' => 0.0, + 'bar' => 1, + ], + true, + ], + [ + [ + 'foo' => 'permit_empty|required_without[bar]', + ], + [ + 'foo' => '', + 'bar' => 1, + ], + true, + ], ]; }