Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[10.x] Feat: Add color_hex validation rule #49056

Merged
merged 3 commits into from
Nov 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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