Skip to content

Commit

Permalink
Add RegexValidator
Browse files Browse the repository at this point in the history
  • Loading branch information
sukhwinder33445 committed Oct 10, 2022
1 parent bc765d3 commit 5dd0fbd
Showing 1 changed file with 72 additions and 0 deletions.
72 changes: 72 additions & 0 deletions src/RegexValidator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?php

namespace ipl\Validator;

use Exception;
use ipl\I18n\Translation;

/**
* Validates value with given regex pattern
*
* Available options:
* - pattern (string, Regex pattern)
* - notMatchMessage (string, Message to show if value isn't valid, default null)
*/
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 5dd0fbd

Please sign in to comment.