Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -948,6 +948,12 @@ Field under this rule may be empty.

</details>

<details><summary><strong>string</strong></summary>

Field under this rule must be a string.

</details>

## Register/Override Rule

Another way to use custom validation rule is to create a class extending `Rakit\Validation\Rule`.
Expand Down
23 changes: 23 additions & 0 deletions src/Rules/Stringy.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

namespace Rakit\Validation\Rules;

use Rakit\Validation\Rule;

class Stringy extends Rule
{

/** @var string */
protected $message = "The :attribute only allows a string";

/**
* Check the $value is valid
*
* @param mixed $value
* @return bool
*/
public function check($value): bool
{
return is_string($value);
}
}
1 change: 1 addition & 0 deletions src/Validator.php
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ protected function registerBaseValidators()
'defaults' => new Rules\Defaults,
'default' => new Rules\Defaults, // alias of defaults
'nullable' => new Rules\Nullable,
'string' => new Rules\Stringy,
];

foreach ($baseValidator as $key => $validator) {
Expand Down
33 changes: 33 additions & 0 deletions tests/Rules/StringyTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

namespace Rakit\Validation\Tests;

use Rakit\Validation\Rules\Stringy;
use PHPUnit\Framework\TestCase;
use stdClass;

class StringyTest extends TestCase
{

public function setUp()
{
$this->rule = new Stringy;
}

public function testValids()
{
$this->assertTrue($this->rule->check('foo'));
$this->assertTrue($this->rule->check('123asd'));
$this->assertTrue($this->rule->check('asd123'));
$this->assertTrue($this->rule->check('foo123bar'));
$this->assertTrue($this->rule->check('foo bar'));
$this->assertTrue($this->rule->check('<p><a href="#">Lorem ipsum dolor sit amet</a> cum omnis voluptatum! </p>'));
}

public function testInvalids()
{
$this->assertFalse($this->rule->check(2));
$this->assertFalse($this->rule->check([]));
$this->assertFalse($this->rule->check(new stdClass));
}
}