Skip to content

Commit

Permalink
[9.x] Add decimal validation rule (#45356)
Browse files Browse the repository at this point in the history
* Add `decimal` validation rule

* formatting

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
RaazPuspa and taylorotwell committed Dec 19, 2022
1 parent 2007b7f commit 57eca0c
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/Illuminate/Validation/Concerns/ValidatesAttributes.php
Expand Up @@ -554,6 +554,32 @@ public function validateDateEquals($attribute, $value, $parameters)
return $this->compareDates($attribute, $value, $parameters, '=');
}

/**
* Validate that an attribute has a given number of decimal places.
*
* @param string $attribute
* @param mixed $value
* @param array<int, int|string> $parameters
* @return bool
*/
public function validateDecimal($attribute, $value, $parameters)
{
if (!$this->validateNumeric($attribute, $value)) {
return false;
}

$this->requireParameterCount(1, $parameters, 'decimal');

$matches = [];

preg_match('/^\d*.(\d*)$/', $value, $matches);

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

return $decimals >= $parameters[0] &&
(! isset($parameters[1]) || $decimals <= $parameters[1]);
}

/**
* Validate that an attribute is different from another attribute.
*
Expand Down
37 changes: 37 additions & 0 deletions tests/Validation/ValidationValidatorTest.php
Expand Up @@ -2448,6 +2448,43 @@ public function testValidateInteger()
$this->assertTrue($v->passes());
}

public function testValidateDecimal()
{
$trans = $this->getIlluminateArrayTranslator();
$v = new Validator($trans, ['foo' => 'asdad'], ['foo' => 'Decimal:2,3']);
$this->assertFalse($v->passes());

$v = new Validator($trans, ['foo' => '1.2345'], ['foo' => 'Decimal:2,3']);
$this->assertFalse($v->passes());

$v = new Validator($trans, ['foo' => '1.234'], ['foo' => 'Decimal:2,3']);
$this->assertTrue($v->passes());

$v = new Validator($trans, ['foo' => '1.23'], ['foo' => 'Decimal:2,3']);
$this->assertTrue($v->passes());

$v = new Validator($trans, ['foo' => '1.2'], ['foo' => 'Decimal:2,3']);
$this->assertFalse($v->passes());

$v = new Validator($trans, ['foo' => '1.234'], ['foo' => 'Decimal:2']);
$this->assertTrue($v->passes());

$v = new Validator($trans, ['foo' => '1.23'], ['foo' => 'Decimal:2']);
$this->assertTrue($v->passes());

$v = new Validator($trans, ['foo' => '1.2'], ['foo' => 'Decimal:2']);
$this->assertFalse($v->passes());

$v = new Validator($trans, ['foo' => '1'], ['foo' => 'Decimal:0,1']);
$this->assertTrue($v->passes());

$v = new Validator($trans, ['foo' => '1.2'], ['foo' => 'Decimal:0,1']);
$this->assertTrue($v->passes());

$v = new Validator($trans, ['foo' => '1.23'], ['foo' => 'Decimal:0,1']);
$this->assertFalse($v->passes());
}

public function testValidateInt()
{
$trans = $this->getIlluminateArrayTranslator();
Expand Down

0 comments on commit 57eca0c

Please sign in to comment.