47

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();
}
7
  • you have 140 names w3schools.com/colors/colors_names.asp so check them all .. good luck Commented Jan 28, 2018 at 9:34
  • that links to a jQuery answer for a non-jQuery question, overly complex as usual... Commented Jan 28, 2018 at 10:25
  • >>"it a commentary for someone how did 0 effort.." - keep calm, life is beatiful) Commented Jan 28, 2018 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 ? Commented Jan 28, 2018 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): stackoverflow.com/questions/46155/… Commented Jan 28, 2018 at 10:45

7 Answers 7

75

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 Jonh Smith noted 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"

Sign up to request clarification or add additional context in comments.

1 Comment

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

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. 

4 Comments

Excellent. I think today that should be the best answer.
But this does not work on the node side
@Autumn, you mean it can cause problem in next js?
Specifically, it apparently doesn't work in Jest, since the library doesn't actually load in support.
39

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.

3 Comments

Thank You much! Great! updated question with final version
Nice and pretty. Would give it a heart eyes emoji
When you pass a hex as a argument, it transform it to rgb (IDK why). Checking if s.color has value is enough to know if the color is valid or not.
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;
  }
}

1 Comment

What about rgba(47, 79, 79, 1)? This return false.
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.)

2 Comments

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?
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.
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;
}

Comments

-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?

1 Comment

Greetings Mr.Yannick! No) I need to dynamically check if color 'name' is valid html color

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.