Skip to content

Commit

Permalink
Merge pull request tempestphp#72 from aidan-casey/add-regex-rule
Browse files Browse the repository at this point in the history
Adds regex validation rule
  • Loading branch information
brendt committed Feb 21, 2024
2 parents 975db11 + 3cddb25 commit 72e0b3b
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/Validation/Rules/Regex.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

declare(strict_types=1);

namespace Tempest\Validation\Rules;

use Attribute;
use Tempest\Interface\Rule;

#[Attribute]
final readonly class Regex implements Rule
{
public function __construct(private string $pattern)
{
}

public function isValid(mixed $value): bool
{
return preg_match($this->pattern, $value) === 1;
}

public function message(): string
{
return "The value must match the regular expression pattern: $this->pattern";
}
}
28 changes: 28 additions & 0 deletions tests/Validation/Rules/RegexTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

namespace Tests\Tempest\Validation\Rules;

use PHPUnit\Framework\TestCase;
use Tempest\Validation\Rules\Regex;

class RegexTest extends TestCase
{
public function test_regex_rule()
{
$rule = new Regex('/^[aA][bB]$/');

$this->assertSame(
'The value must match the regular expression pattern: /^[aA][bB]$/',
$rule->message()
);

$this->assertFalse($rule->isValid('cd'));
$this->assertFalse($rule->isValid('za'));

$this->assertTrue($rule->isValid('ab'));
$this->assertTrue($rule->isValid('AB'));
$this->assertTrue($rule->isValid('Ab'));
}
}

0 comments on commit 72e0b3b

Please sign in to comment.