Skip to content

Commit

Permalink
[9.x] Improve decimal shape validation (#47957)
Browse files Browse the repository at this point in the history
* improve decimal shape validation

* Additional tests
  • Loading branch information
timacdonald committed Aug 7, 2023
1 parent 5366a90 commit 75d317a
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/Illuminate/Validation/Concerns/ValidatesAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -593,7 +593,9 @@ public function validateDecimal($attribute, $value, $parameters)

$matches = [];

preg_match('/^[+-]?\d*.(\d*)$/', $value, $matches);
if (preg_match('/^[+-]?\d*\.?(\d*)$/', $value, $matches) !== 1) {
return false;
}

$decimals = strlen(end($matches));

Expand Down
44 changes: 44 additions & 0 deletions tests/Validation/ValidationValidatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2860,6 +2860,50 @@ public function testValidateDecimal()

$v = new Validator($trans, ['foo' => '1.88888888888888888888'], ['foo' => 'Decimal:20|Max:1.88888888888888888888']);
$this->assertTrue($v->passes());

$v = new Validator($trans, [
// these are the same number
'decimal' => '0.555',
'scientific' => '5.55e-1',
], [
'decimal' => 'Decimal:0,2',
'scientific' => 'Decimal:0,2',
]);
$this->assertSame(['decimal', 'scientific'], $v->errors()->keys());

$v = new Validator($trans, [
// these are the same number
'decimal' => '0.555',
'scientific' => '5.55e-1',
], [
'decimal' => 'Decimal:0,3',
'scientific' => 'Decimal:0,3',
]);
$this->assertSame(['scientific'], $v->errors()->keys());

$v = new Validator($trans, ['foo' => '+'], ['foo' => 'Decimal:0,2']);
$this->assertTrue($v->fails());
$v = new Validator($trans, ['foo' => '-'], ['foo' => 'Decimal:0,2']);
$this->assertTrue($v->fails());
$v = new Validator($trans, ['foo' => '10@12'], ['foo' => 'Decimal:0,2']);
$this->assertTrue($v->fails());

$v = new Validator($trans, ['foo' => '+123'], ['foo' => 'Decimal:0,2']);
$this->assertTrue($v->passes());
$v = new Validator($trans, ['foo' => '-123'], ['foo' => 'Decimal:0,2']);
$this->assertTrue($v->passes());
$v = new Validator($trans, ['foo' => '+123.'], ['foo' => 'Decimal:0,2']);
$this->assertTrue($v->passes());
$v = new Validator($trans, ['foo' => '-123.'], ['foo' => 'Decimal:0,2']);
$this->assertTrue($v->passes());
$v = new Validator($trans, ['foo' => '123.'], ['foo' => 'Decimal:0,2']);
$this->assertTrue($v->passes());
$v = new Validator($trans, ['foo' => '123.'], ['foo' => 'Decimal:0,2']);
$this->assertTrue($v->passes());
$v = new Validator($trans, ['foo' => '123.34'], ['foo' => 'Decimal:0,2']);
$this->assertTrue($v->passes());
$v = new Validator($trans, ['foo' => '123.34'], ['foo' => 'Decimal:0,2']);
$this->assertTrue($v->passes());
}

public function testValidateInt()
Expand Down

0 comments on commit 75d317a

Please sign in to comment.