Skip to content

Commit eb2f51b

Browse files
authored
[8.x] Handle type mismatch in the enum validation rule (#40362)
* handle type mismatch in the enum validation rule * switch to catching TypeError
1 parent 55ea49b commit eb2f51b

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

src/Illuminate/Validation/Rules/Enum.php

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace Illuminate\Validation\Rules;
44

55
use Illuminate\Contracts\Validation\Rule;
6+
use TypeError;
67

78
class Enum implements Rule
89
{
@@ -37,7 +38,11 @@ public function passes($attribute, $value)
3738
return false;
3839
}
3940

40-
return ! is_null($this->type::tryFrom($value));
41+
try {
42+
return ! is_null($this->type::tryFrom($value));
43+
} catch (TypeError $e) {
44+
return false;
45+
}
4146
}
4247

4348
/**

tests/Validation/ValidationEnumRuleTest.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,22 @@ public function testValidationFailsOnPureEnum()
131131
$this->assertTrue($v->fails());
132132
}
133133

134+
public function testValidationFailsWhenProvidingStringToIntegerType()
135+
{
136+
$v = new Validator(
137+
resolve('translator'),
138+
[
139+
'status' => 'abc',
140+
],
141+
[
142+
'status' => new Enum(IntegerStatus::class),
143+
]
144+
);
145+
146+
$this->assertTrue($v->fails());
147+
$this->assertEquals(['The selected status is invalid.'], $v->messages()->get('status'));
148+
}
149+
134150
protected function setUp(): void
135151
{
136152
$container = Container::getInstance();

0 commit comments

Comments
 (0)