Skip to content

Commit c421389

Browse files
add alpha_spaces rule
1 parent 130f61b commit c421389

File tree

3 files changed

+64
-0
lines changed

3 files changed

+64
-0
lines changed

README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -667,6 +667,12 @@ The field under this rule may have alpha-numeric characters, as well as dashes a
667667

668668
</details>
669669

670+
<details><summary><strong>alpha_spaces</strong></summary>
671+
672+
The field under this rule may have alpha characters, as well as spaces.
673+
674+
</details>
675+
670676
<details><summary><strong>in</strong>:value_1,value_2,...</summary>
671677

672678
The field under this rule must be included in the given list of values.

src/Rules/AlphaSpaces.php

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<?php
2+
3+
namespace Rakit\Validation\Rules;
4+
5+
use Rakit\Validation\Rule;
6+
7+
class AlphaSpaces extends Rule
8+
{
9+
10+
/** @var string */
11+
protected $message = "The :attribute may only allows alphabet and spaces";
12+
13+
/**
14+
* Check the $value is valid
15+
*
16+
* @param mixed $value
17+
* @return bool
18+
*/
19+
public function check($value): bool
20+
{
21+
if (! is_string($value) && ! is_numeric($value)) {
22+
return false;
23+
}
24+
25+
return preg_match('/^[\pL\pM\s]+$/u', $value) > 0;
26+
}
27+
}

tests/Rules/AlphaSpacesTest.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<?php
2+
3+
namespace Rakit\Validation\Tests;
4+
5+
use Rakit\Validation\Rules\AlphaSpaces;
6+
use PHPUnit\Framework\TestCase;
7+
8+
class AlphaSpacesTest extends TestCase
9+
{
10+
11+
public function setUp()
12+
{
13+
$this->rule = new AlphaSpaces;
14+
}
15+
16+
public function testValids()
17+
{
18+
$this->assertTrue($this->rule->check('abc'));
19+
$this->assertTrue($this->rule->check('foo bar'));
20+
$this->assertTrue($this->rule->check('foo bar bar'));
21+
}
22+
23+
public function testInvalids()
24+
{
25+
$this->assertFalse($this->rule->check('123'));
26+
$this->assertFalse($this->rule->check('123abc'));
27+
$this->assertFalse($this->rule->check('abc123'));
28+
$this->assertFalse($this->rule->check('foo_123'));
29+
$this->assertFalse($this->rule->check('213-foo'));
30+
}
31+
}

0 commit comments

Comments
 (0)