If a color string is a number, then we can use a RegExp
to check if it's a valid CSS color. But what if it's a word?
I have code that generates controls dynamically from colors arguments. But instead of color, there could be null
, ""
, or random words. Is there a way to check color name with Javascript?
Update: Thank you much for the great answer! :) My final version is below (added a toLowerCase()
check because the color could be "Green"
, "Red"
, etc.).
function isValidColor(strColor) { var s = new Option().style; s.color = strColor; // return 'false' if color wasn't assigned return s.color == strColor.toLowerCase(); }
The W3C HTML and CSS standards have listed only 16 valid color names: aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, purple, red, silver, teal, white, and yellow. If you want valid HTML or CSS use the HEX values instead.
The most common way to specify colors in CSS is to use their hexadecimal (or hex) values. Hex values are actually just a different way to represent RGB values. Instead of using three numbers between 0 and 255, you use six hexadecimal numbers. Hex numbers can be 0-9 and A-F.
Value is the measurement of the amount of black or white mixed into a pure hue. By adding black to the color, the value is made darker, resulting in what is referred to as a “shade.” When white is added to a color, the result is a lighter value, which is referred to as a “tint.”
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With