-
-
Notifications
You must be signed in to change notification settings - Fork 3
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
Showing
1 changed file
with
53 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,53 @@ | ||
<?php | ||
|
||
namespace Zemit\Validation\Validator; | ||
|
||
use Phalcon\Validation; | ||
use Phalcon\Validation\AbstractValidator; | ||
use Phalcon\Validation\ValidatorInterface; | ||
|
||
class Color extends AbstractValidator implements ValidatorInterface | ||
{ | ||
protected $template = 'Field :field must be a valid color in hexadecimal format (e.g., #RRGGBB)'; | ||
|
||
/** | ||
* Constructor | ||
* | ||
* @param array options = [ | ||
* 'message' => '', | ||
* 'template' => '', | ||
* 'allowEmpty' => false | ||
* ] | ||
*/ | ||
public function __construct(array $options = []) | ||
{ | ||
parent::__construct($options); | ||
} | ||
|
||
public function validate(Validation $validation, $field): bool | ||
{ | ||
$value = $validation->getValue($field); | ||
|
||
if (!$this->isValidColor($value)) { | ||
|
||
$validation->appendMessage( | ||
$this->messageFactory($validation, $field) | ||
); | ||
|
||
return false; | ||
} | ||
|
||
return true; | ||
} | ||
|
||
/** | ||
* Check if a given color is in a valid hexadecimal format. | ||
*/ | ||
private function isValidColor(?string $color): bool | ||
{ | ||
// Hexadecimal color regex pattern | ||
$pattern = '/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/'; | ||
|
||
return preg_match($pattern, $color) === 1; | ||
} | ||
} |