瀏覽代碼

Enhance hex value color validation.

Maciej Gołaszewski 5 年之前
父節點
當前提交
b9264a4c7d

+ 14 - 1
packages/ckeditor5-engine/src/view/styles/utils.js

@@ -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.
@@ -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 );
 }
 

+ 9 - 5
packages/ckeditor5-engine/tests/view/styles/utils.js

@@ -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', () => {