-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
bc765d3
commit 5dd0fbd
Showing
1 changed file
with
72 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |