Skip to content
This repository has been archived by the owner on Jun 26, 2020. It is now read-only.

Commit

Permalink
Enhance hex value color validation.
Browse files Browse the repository at this point in the history
  • Loading branch information
jodator committed Feb 7, 2020
1 parent ecaf056 commit d6eab33
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 6 deletions.
15 changes: 14 additions & 1 deletion src/view/styles/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@
* @module engine/view/styles/utils
*/

const colorRegExp = /^([#0-9A-Fa-f]{3,9}$|0$|rgba?\(|hsla?\(|[a-zA-Z]+$)/;
const colorRegExp = /^(0$|rgba?\(|hsla?\(|[a-zA-Z]+$)/;

const HEX_VALUE_REGEXP = /^[0-9a-fA-F]+$/;
const validHexLengths = [ 3, 4, 6, 8 ];

/**
* Checks if string contains [color](https://developer.mozilla.org/en-US/docs/Web/CSS/color) CSS value.
Expand All @@ -16,6 +19,16 @@ const colorRegExp = /^([#0-9A-Fa-f]{3,9}$|0$|rgba?\(|hsla?\(|[a-zA-Z]+$)/;
* @returns {Boolean}
*/
export function isColor( string ) {
if ( string.startsWith( '#' ) ) {
const hexValue = string.substr( 1 );

if ( !validHexLengths.includes( hexValue.length ) ) {
return false;
}

return HEX_VALUE_REGEXP.test( hexValue );
}

return colorRegExp.test( string );
}

Expand Down
14 changes: 9 additions & 5 deletions tests/view/styles/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,22 +12,26 @@ import {
isLineStyle
} from '../../../src/view/styles/utils';

describe( 'Styles utils', () => {
describe.only( 'Styles utils', () => {
describe( 'isColor()', () => {
it( 'returns true for #RGB color', () => {
testValues( [ '#f00', '#ba2' ], isColor );
testValues( [ '#f00', '#ba2', '#F00', '#BA2', '#AbC' ], isColor );
} );

it( 'returns true for #RRGGBB color', () => {
testValues( [ '#ff0000', '#bbaa22' ], isColor );
testValues( [ '#ff0000', '#bbaa22', '#FF0000', '#BBAA22', '#AabBCC' ], isColor );
} );

it( 'returns true for #RGBA color', () => {
testValues( [ '#f000', '#ba24' ], isColor );
testValues( [ '#f000', '#ba24', '#F000', '#BA24', '#aBcD' ], isColor );
} );

it( 'returns true for #RRGGBBAA color', () => {
testValues( [ '#ff000000', '#bbaa2244' ], isColor );
testValues( [ '#ff000000', '#bbaa2244', '#FF000000', '#BBAA2244', '#AabBCCdd' ], isColor );
} );

it( 'returns false for invalid # color', () => {
testValues( [ '#ttt', '#1', '#12', '#12345' ], value => !isColor( value ) );
} );

it( 'returns true for rgb() color', () => {
Expand Down

0 comments on commit d6eab33

Please sign in to comment.