Skip to content

Commit

Permalink
Add RegExValidator
Browse files Browse the repository at this point in the history
  • Loading branch information
sukhwinder33445 committed Aug 18, 2022
1 parent 97bfb7c commit 2ec7d8e
Showing 1 changed file with 66 additions and 0 deletions.
66 changes: 66 additions & 0 deletions src/RegExValidator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

namespace ipl\Validator;

use Exception;
use ipl\I18n\Translation;

class RegExValidator extends BaseValidator
{
use Translation;

protected $pattern;

protected $notMatchMessage;

public function __construct($pattern)
{
if (is_array($pattern)) {
if (! isset($pattern['pattern'])) {
throw new Exception("Missing option 'pattern'");
}

$this->pattern = $pattern['pattern'];
$this->notMatchMessage = $pattern['notMatchMessage'] ?? null;

} else {
$this->pattern = (string) $pattern;
}
}

public function isValid($value)
{
// Multiple isValid() calls must not stack validation messages
$this->clearMessages();

if (empty($value)) {
return true;
}

$status = @preg_match($this->pattern, $value);
if ($status === false) {
$this->addMessage(sprintf(
"There was an internal error while using the pattern '%s'",
$this->pattern
));

return false;
}

if ($status === 0) {
if (empty($this->notMatchMessage)) {
$this->addMessage(sprintf(
$this->translate("'%s' does not match against pattern '%s'"),
$value,
$this->pattern
));
} else {
$this->addMessage($this->notMatchMessage);
}

return false;
}

return true;
}
}

0 comments on commit 2ec7d8e

Please sign in to comment.