Javascript – check if string is valid CSS color?

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”

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)