Skip to content

Commit 9edbafc

Browse files
committed
Add digits rule
1 parent e3473f8 commit 9edbafc

File tree

3 files changed

+52
-0
lines changed

3 files changed

+52
-0
lines changed

src/Rules/Digits.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<?php
2+
3+
namespace Rakit\Validation\Rules;
4+
5+
use Rakit\Validation\Rule;
6+
7+
class Digits extends Rule
8+
{
9+
10+
protected $message = "The :attribute must be numeric and must have an exact length of :length";
11+
12+
protected $fillable_params = ['length'];
13+
14+
public function check($value)
15+
{
16+
$this->requireParameters($this->fillable_params);
17+
18+
$length = (int) $this->parameter('length');
19+
20+
return ! preg_match('/[^0-9]/', $value)
21+
&& strlen((string) $value) == $length;
22+
}
23+
24+
}

src/Validator.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@ protected function registerBaseValidators()
107107
'lowercase' => new Rules\Lowercase,
108108
'uppercase' => new Rules\Uppercase,
109109
'json' => new Rules\Json,
110+
'digits' => new Rules\Digits,
110111
'defaults' => new Rules\Defaults,
111112
'default' => new Rules\Defaults, // alias of defaults
112113
];

tests/Rules/DigitsTest.php

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<?php
2+
3+
use Rakit\Validation\Rules\Digits;
4+
5+
class DigitsTest extends PHPUnit_Framework_TestCase
6+
{
7+
8+
public function setUp()
9+
{
10+
$this->rule = new Digits;
11+
}
12+
13+
public function testValids()
14+
{
15+
$this->assertTrue($this->rule->fillParameters([4])->check(1243));
16+
$this->assertTrue($this->rule->fillParameters([6])->check(124567));
17+
$this->assertTrue($this->rule->fillParameters([3])->check('123'));
18+
}
19+
20+
public function testInvalids()
21+
{
22+
$this->assertFalse($this->rule->fillParameters([7])->check(12345678));
23+
$this->assertFalse($this->rule->fillParameters([4])->check(12));
24+
$this->assertFalse($this->rule->fillParameters([3])->check('foo'));
25+
}
26+
27+
}

0 commit comments

Comments
 (0)