Skip to content
Snippets Groups Projects
Verified Commit de56b259 authored by Lee Rowlands's avatar Lee Rowlands
Browse files

Issue #3056454 by Krzysztof Domański, John Cook, johndevman: Hexadecimal...

Issue #3056454 by Krzysztof Domański, John Cook, johndevman: Hexadecimal validation returns true if the color contains multiple hashes (e.g. '###FF0')
parent 006e1794
No related branches found
No related tags found
No related merge requests found
......@@ -18,16 +18,10 @@ class Color {
* TRUE if $hex is valid or FALSE if it is not.
*/
public static function validateHex($hex) {
// Must be a string.
$valid = is_string($hex);
// Hash prefix is optional.
$hex = ltrim($hex, '#');
// Must be either RGB or RRGGBB.
$length = mb_strlen($hex);
$valid = $valid && ($length === 3 || $length === 6);
// Must be a valid hex value.
$valid = $valid && ctype_xdigit($hex);
return $valid;
if (!is_string($hex)) {
return FALSE;
}
return preg_match('/^[#]?([0-9a-fA-F]{3}){1,2}$/', $hex) === 1;
}
/**
......
......@@ -12,6 +12,60 @@
*/
class ColorTest extends TestCase {
/**
* @covers \Drupal\Component\Utility\Color::validateHex
*
* @param bool $expected
* The expected result of validation.
* @param string $value
* The hex color value.
*
* @dataProvider providerTestValidateHex()
*/
public function testValidateHex($expected, $value) {
$this->assertSame($expected, Color::validateHex($value));
}
/**
* Provides data for testValidateHex().
*/
public function providerTestValidateHex() {
return [
// Tests length.
[FALSE, ''],
[FALSE, '#'],
[FALSE, '1'],
[FALSE, '#1'],
[FALSE, '12'],
[FALSE, '#12'],
[TRUE, '123'],
[TRUE, '#123'],
[FALSE, '1234'],
[FALSE, '#1234'],
[FALSE, '12345'],
[FALSE, '#12345'],
[TRUE, '123456'],
[TRUE, '#123456'],
[FALSE, '1234567'],
[FALSE, '#1234567'],
// Tests valid hex value.
[TRUE, 'abcdef'],
[TRUE, 'ABCDEF'],
[TRUE, 'A0F1B1'],
[FALSE, 'WWW'],
[FALSE, '#123##'],
[FALSE, '@a0055'],
// Tests the data type.
[FALSE, 123456],
// Tests multiple hash prefix.
[FALSE, '###F00'],
// Tests spaces.
[FALSE, ' #123456'],
[FALSE, '123456 '],
[FALSE, '#12 3456'],
];
}
/**
* Tests Color::hexToRgb().
*
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment