Javascript - check if string is valid CSS color?

I needed to validate CSS colors and all other attributes. I found this wonderful solution to be shorter and more robust as it uses built in Web APIs CSS.supports() method.

CSS.supports(propertyName, propertyValue)

CSS.supports('color','red') 
//True.
CSS.supports('color', '#007')
//True. 

CSS.supports('color', 'random')
//False. 
CSS.supports('colours', 'red')
//False. 

The accepted answer is almost correct, but some color values will be converted on some browsers -- at least Chrome converts hex RGB values #000000 to rgb(0, 0, 0).

However, if you set the style.color to an invalid value, you will get an empty string when checking it:

const isColor = (strColor) => {
  const s = new Option().style;
  s.color = strColor;
  return s.color !== '';
}

As Mr Smith not4ed in the comments, the above also returns true for the keywords unset, initial, inherit. Whether these should be counted as valid colors probably depends on the application/context"


Here's a simple function that checks color name support in the current browser:

function isColor(strColor){
  var s = new Option().style;
  s.color = strColor;
  return s.color == strColor;
}

// try it out
isColor("red");   // true
isColor("reds");  // false

Since an invalid CSS property value will not persist, we can compare an attempted set value with the value we meant to set, and if they match, we know the color/property is valid.

Note this will also approve hex, RGB, etc. You can screen those out with a RegExp or two if that's an issue for your application.