diff --git a/src/RegexValidator.php b/src/RegexValidator.php new file mode 100644 index 0000000..9067d6a --- /dev/null +++ b/src/RegexValidator.php @@ -0,0 +1,70 @@ +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(); + + $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; + } +}