diff --git a/src/Validator.php b/src/Validator.php index 67f9a8e..603e627 100755 --- a/src/Validator.php +++ b/src/Validator.php @@ -7,7 +7,7 @@ * @license MIT https://github.com/SandroMiguel/verum-php/blob/master/LICENSE * @author Sandro Miguel Marques * @link https://github.com/SandroMiguel/verum-php - * @version 4.2.1 (2024-03-20) + * @version 4.2.2 (2024-03-21) */ declare(strict_types=1); @@ -222,6 +222,10 @@ public function validate(): bool \count($fieldValue) - 1 ) ) { + if ($this->debugMode) { + echo "\n2.3 Field is an indexed array - Ignore"; + } + continue; } @@ -457,6 +461,11 @@ private function getMultiNameFieldValues(string $fieldName): array $multiNameFieldValues = []; + // Ensure that the field name is in the payload and validate it against null + if (\count($fieldValues) === 0) { + return [$fieldName => null]; + } + foreach ($fieldValues as $fullFieldName => $value) { if (\strpos($fullFieldName, $baseFieldName) !== 0) { continue; diff --git a/tests/ValidatorTest.php b/tests/ValidatorTest.php index b065406..da7b4f8 100755 --- a/tests/ValidatorTest.php +++ b/tests/ValidatorTest.php @@ -872,6 +872,53 @@ public function testValidateMultiNameFieldsFullnameMatch(): void ); } + /** + * Tests the validation when a multi-name field defined in the rules does + * not exist in the payload. + */ + public function testValidateMultiNameFieldNotInPayload(): void + { + $fieldValues = [ + 'age' => 'Text value', + ]; + + $fieldRules = [ + 'age' => [ + 'label' => 'Age', + 'rules' => [ + RuleEnum::NUMERIC, + ], + ], + 'multiName.*' => [ + 'rules' => [RuleEnum::REQUIRED], + ], + ]; + + $expected = [ + 'age' => [ + 'label' => 'Age', + 'rules' => [ + 'numeric' => 'The "Age" field must be numeric.', + ], + ], + 'multiName.*' => [ + 'label' => null, + 'rules' => [ + 'required' => 'This field is required.', + ], + ], + ]; + + $validator = new Validator($fieldValues, $fieldRules, debugMode: true); + $validator->validate(); + $errors = $validator->getErrors(); + + $this->assertEquals( + \json_encode($expected), + \json_encode($errors) + ); + } + /** * Test validation with a payload containing numeric keys in an array field. */ @@ -905,7 +952,8 @@ public function testValidationWithNumericKeysInArrayField(): void } /** - * Test validation with an empty idTranslationValues field, which should fail due to its required nature. + * Test validation with an empty idTranslationValues field, which should + * fail due to its required nature. */ public function testValidationWithEmptyIdTranslationValuesField(): void { @@ -944,6 +992,9 @@ public function testValidationWithEmptyIdTranslationValuesField(): void $errors = $validator->getErrors(); // Assert that the validation errors match the expected errors - $this->assertEquals(json_encode($expectedErrors), json_encode($errors)); + $this->assertEquals( + \json_encode($expectedErrors), + \json_encode($errors) + ); } }