diff --git a/src/Hex.php b/src/Hex.php index 16d356a..3ab9b20 100644 --- a/src/Hex.php +++ b/src/Hex.php @@ -11,9 +11,16 @@ class Hex implements Rule */ protected $forceFull; - public function __construct($forceFull = false) + /** + * @var bool + */ + protected $allowAlpha; + + public function __construct($forceFull = false, $allowAlpha = false) { $this->forceFull = $forceFull; + + $this->allowAlpha = $allowAlpha; } /** @@ -32,6 +39,14 @@ public function passes($attribute, $value) $pattern .= '|[a-fA-F0-9]{3}'; } + if ($this->allowAlpha) { + $pattern .= '|[a-fA-F0-9]{8}'; + + if (!$this->forceFull) { + $pattern .= '|[a-fA-F0-9]{4}'; + } + } + $pattern .= ')$/'; return (bool) preg_match($pattern, $value); diff --git a/tests/Feature/HexTest.php b/tests/Feature/HexTest.php index 2f0ac1c..dc2fbfc 100644 --- a/tests/Feature/HexTest.php +++ b/tests/Feature/HexTest.php @@ -37,4 +37,20 @@ public function three_characters_with_hash() $this->assertTrue($this->validator('#fff', false)->passes()); // full } + + public function eight_characters_with_hash() + { + $this->assertTrue($this->validator('#ff008000')->fails()); + $this->assertTrue($this->validator('#fg00800g', true, true)->fails()); + $this->assertTrue($this->validator('#ff008000', true, true)->passes()); + } + + /** @test */ + public function four_characters_with_hash() + { + $this->assertTrue($this->validator('#ffff', true, true)->passes()); + $this->assertTrue($this->validator('#ffff', true, false)->fails()); + $this->assertTrue($this->validator('#gggg', true, true)->fails()); + $this->assertTrue($this->validator('#ffff', false, true)->passes()); + } }