Skip to content

Commit

Permalink
[10.x] Feat: Add color_hex validation rule (#49056)
Browse files Browse the repository at this point in the history
* Add color_hex validation rule

* fix: styleci

* formatting

---------

Co-authored-by: Taylor Otwell <[email protected]>
  • Loading branch information
nikopeikrishvili and taylorotwell authored Nov 20, 2023
1 parent 5f103f0 commit 85fcda7
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/Illuminate/Translation/lang/en/validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
'numeric' => 'The :attribute field must be greater than or equal to :value.',
'string' => 'The :attribute field must be greater than or equal to :value characters.',
],
'hex_color' => 'The :attribute field must be a valid hexadecimal color.',
'image' => 'The :attribute field must be an image.',
'in' => 'The selected :attribute is invalid.',
'in_array' => 'The :attribute field must exist in :other.',
Expand Down
12 changes: 12 additions & 0 deletions src/Illuminate/Validation/Concerns/ValidatesAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -1270,6 +1270,18 @@ public function validateUppercase($attribute, $value, $parameters)
return Str::upper($value) === $value;
}

/**
* Validate that an attribute is a valid HEX color.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function validateHexColor($attribute, $value)
{
return preg_match('/^#(?:[0-9a-fA-F]{3}){1,2}$/', $value) === 1;
}

/**
* Validate the MIME type of a file is an image MIME type.
*
Expand Down
13 changes: 13 additions & 0 deletions tests/Validation/ValidationValidatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1925,6 +1925,19 @@ public function testValidateInArray()
$this->assertSame('The value of foo.2 does not exist in bar.*.', $v->messages()->first('foo.2'));
}

public function testValidateHexColor()
{
$trans = $this->getIlluminateArrayTranslator();
$v = new Validator($trans, ['color'=> '#FFFFFF'], ['color'=>'hex_color']);
$this->assertTrue($v->passes());
$v = new Validator($trans, ['color'=> '#FFF'], ['color'=>'hex_color']);
$this->assertTrue($v->passes());
$v = new Validator($trans, ['color'=> '#GGG'], ['color'=>'hex_color']);
$this->assertFalse($v->passes());
$v = new Validator($trans, ['color'=> '#GGGGGGG'], ['color'=>'hex_color']);
$this->assertFalse($v->passes());
}

public function testValidateConfirmed()
{
$trans = $this->getIlluminateArrayTranslator();
Expand Down

0 comments on commit 85fcda7

Please sign in to comment.