Skip to content

Commit 1462e2b

Browse files
feat: Update validation error to include original value
Prior, the validation error may contain the cast-value which can be confusing when reporting the validation error to users.
1 parent aa39c44 commit 1462e2b

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

src/Fields/BaseField.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,12 @@ public function validateValue($val)
171171

172172
return [];
173173
} catch (FieldValidationException $e) {
174+
foreach ($e->validationErrors as $ve) {
175+
// Replace the cast-value for the violation, with the original value.
176+
// This so the error message contains the original representation of the invalid value.
177+
$ve->extraDetails['value'] = $val;
178+
}
179+
174180
return $e->validationErrors;
175181
}
176182
}

tests/Fields/BaseFieldTest.php

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Fields;
6+
7+
use frictionlessdata\tableschema\Fields\BaseField;
8+
use PHPUnit\Framework\TestCase;
9+
use ZBan\Tests\PHPUnit\Framework\ZBanTestCase;
10+
11+
/**
12+
* @covers \frictionlessdata\tableschema\Fields\BaseField
13+
*/
14+
class BaseFieldTest extends TestCase
15+
{
16+
public function testPreserveOriginalValueInValidationError(): void
17+
{
18+
$descriptor = (object) [
19+
'name' => 'date_col',
20+
'constraints' => (object) ['minimum' => '2025-07-01']
21+
];
22+
23+
$sut = new class($descriptor) extends BaseField {
24+
protected function validateCastValue($val)
25+
{
26+
// If the logic is wrong, this object will be in the error
27+
// instead of the original date string.
28+
return new \DateTimeImmutable($val);
29+
}
30+
};
31+
32+
$validatedValue = '2025-06-30';
33+
$errors = $sut->validateValue($validatedValue);
34+
35+
self::assertCount(1, $errors);
36+
$error = reset($errors);
37+
self::assertSame(
38+
$validatedValue,
39+
$error->extraDetails['value']
40+
);
41+
}
42+
}

0 commit comments

Comments
 (0)