Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - check if string is valid CSS color?

Tags:

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(); } 
like image 916
Gennady G Avatar asked Jan 28 '18 09:01

Gennady G


People also ask

Is valid CSS color?

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.

How do I identify a color in CSS?

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.

How can you tell if a color is dark or light?

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.”


1 Answers

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"

like image 166
Lee Goddard Avatar answered Oct 06 '22 21:10

Lee Goddard