37

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();
}
MarredCheese
  • 17,541
  • 8
  • 92
  • 91
Gennady G
  • 996
  • 2
  • 11
  • 28
  • you have 140 names https://www.w3schools.com/colors/colors_names.asp so check them all .. good luck – Temani Afif Jan 28 '18 at 09:34
  • that links to a jQuery answer for a non-jQuery question, overly complex as usual... – dandavis Jan 28 '18 at 10:25
  • >>"it a commentary for someone how did 0 effort.." - keep calm, life is beatiful) – Gennady G Jan 28 '18 at 10:30
  • @dandavis i know, i was simply replying to someone who said my comment is ridiculous (he deleted his comment) to show him that with some research we can find a lot of ways, jQuery or not jQuery .. and based on this we can at least do an attempt then we can post question if we face issue. I guess this is how the site works, if am not wrong :) or should we encourage people to consider this website a Free coding service ? – Temani Afif Jan 28 '18 at 10:39
  • i just knew a quick way of doing it and didn't see any good answers already. it's a simple question, but it's not the kind of question that results from mis-implementation; so it's hard for OP to show prior work. Look at what by vote accounts is a good question (no research at all): https://stackoverflow.com/questions/46155/how-can-you-validate-an-email-address-in-javascript?rq=1 – dandavis Jan 28 '18 at 10:45
  • Note that [color names are case-insensitive in CSS](https://www.w3.org/TR/css-color-3/#html4). – MarredCheese Apr 08 '19 at 20:57
  • It seems to be everyone here is using the `new Option()` constructor instead of `document.createElement('div')`. Is there some advantage to this? Am genuinely curious, I didn't know you could make option elements like this, but JSBench seems to find `document.createElement('div')` slightly faster. – Alexander Molloy Jul 24 '19 at 15:59

7 Answers7

70

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"

Lee Goddard
  • 10,680
  • 4
  • 46
  • 63
  • 2
    Note that this function returns 'true' also for the global keywords (unset, initial, inherit) - Whether these should be counted as valid colors probably depends on the application/context. – Jonh Smith Apr 13 '21 at 01:37
44

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. 
Katrpilar
  • 731
  • 5
  • 11
38

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.

MarredCheese
  • 17,541
  • 8
  • 92
  • 91
dandavis
  • 16,370
  • 5
  • 40
  • 36
5

I'm developing an application accepting color names or hex colors. dandavis' answer works just fine for the color names but does not work for hex colors. The value stored in s.color (when assigning '#ff0000') is a RGB code (in this case rgb(255, 0, 0)). Therefore, the comparison s.color == strColor returns false.

Therefore, you need to combine dandavis' solution and the solution given here.

Could look like this:

function isColor(strColor){
  var s = new Option().style;
  s.color = strColor;
  var test1 = s.color == strColor;
  var test2 = /^#[0-9A-F]{6}$/i.test(strColor);
  if(test1 == true || test2 == true){
    return true;
  } else{
    return false;
  }
}
Palle Due
  • 5,929
  • 4
  • 17
  • 32
jsand3k
  • 134
  • 1
  • 4
3

Here is a generic solution to test any CSS property value:

function validCssValue(cssProp,val){
    if(cssProp == "length") return false;
    if(val == "") return true;
    var style = new Option().style;
    if(style[cssProp] != "") return false;
    style[cssProp] = val;
    return style[cssProp] !== "";
}

All properties of new Option().style will be empty when created. Only valid values will update a property, so invalid values will leave the property empty. (Length is a property of the style object, but not a CSS property, so we need to reject trying to test it.)

MacSims
  • 39
  • 4
  • Awesome, just I get confused: if we pass an empty value (empty string `""`) I think this is considered as a not valid CSS property, not? or it's will deleting the property itself from the element style. so, is not wise to return false instead of true in the third line? – Tamsamani Dec 23 '20 at 11:06
  • 1
    For my purposes, empty is a valid value, because that would unset the css property. If your implementation sees empty as invalid, you could change line three to return false. – MacSims Dec 24 '20 at 20:18
1

The input is often incorrect with the output. If you check the length of the values, you get either an empty string or a value in the CSS2 tree

function isColor(string) {
    var s = new Option().style;
    s.color = string;
    return s.color.length > 0;
}
Alper Aydingül
  • 251
  • 1
  • 9
-3
<p class="red"></p>
<p class="yellow"></p>
<p class="white"></p>

$(funtion(){
var obj = $("p");
var ex = $(obj).eq(1);

   $("button").click(funtion(){
   alert(obj);
  });
});

Does this solve the problem?