Skip to content

Commit 4d0b147

Browse files
authored
Preserve original attribute name for nested fields (#3)
preserve original attribute name for nested fields
1 parent d0dceef commit 4d0b147

File tree

3 files changed

+31
-9
lines changed

3 files changed

+31
-9
lines changed

CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,11 @@
22

33
All notable changes to `laravel-json-validation-testing` will be documented in this file.
44

5+
## 1.0.1 - 2022-03-03
6+
7+
**Fixed**
8+
- Preserve original attribute name for nested fields
9+
510
## 1.0.0 - 2022-03-02
611

712
- initial release

src/Validator.php

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -36,30 +36,44 @@ public function getErrorMessage(string $attribute, string|RuleContract $rule): a
3636
$messages = $messages ? (array) $messages : [get_class($rule)];
3737

3838
foreach ($messages as $message) {
39-
$result[] = $this->makeReplacements(
39+
$result[] = $this->buildMessage(
4040
$message,
4141
$attribute,
4242
get_class($rule),
43-
[]
4443
);
4544
}
4645

4746
return $result;
4847
}
4948

50-
$attribute = str_replace(
51-
[$this->dotPlaceholder, '__asterisk__'],
52-
['.', '*'],
53-
$attribute
54-
);
55-
5649
return [
57-
$this->makeReplacements(
50+
$this->buildMessage(
5851
$this->getMessage($attribute, $rule),
5952
$attribute,
6053
$rule,
6154
$parameters
6255
),
6356
];
6457
}
58+
59+
/**
60+
* Build the validation message.
61+
*
62+
* @param string $message
63+
* @param string $attribute
64+
* @param string $rule
65+
* @param array $parameters
66+
* @return string
67+
*/
68+
protected function buildMessage(string $message, string $attribute, string $rule, array $parameters = []): string
69+
{
70+
$result = $this->makeReplacements(...func_get_args());
71+
72+
// Preserve original attribute name if nested (e.g. array.1.field)
73+
if (str_contains($attribute, '.')) {
74+
$result = str_replace($this->getDisplayableAttribute($attribute), $attribute, $result);
75+
}
76+
77+
return $result;
78+
}
6579
}

tests/ValidationRuleMessageTest.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,9 @@
2626
expect(JsonValidation::getRuleErrorMessage('foo', 'required_without:bar'))->toBe([
2727
'The foo field is required when bar is not present.',
2828
]);
29+
expect(JsonValidation::getRuleErrorMessage('foo.1.bar', 'required'))->toBe([
30+
'The foo.1.bar field is required.',
31+
]);
2932
});
3033

3134
it('extracts the error message from a custom rule', function () {

0 commit comments

Comments
 (0)