0

I am adding a div dynamically and adding background colors to these divs. The background color values are coming from the backend, so one div for each colour is added and its background colour is set to that colour. But if some colour that is not valid for CSS background color property comes through, it shows as a white background.

For example 'Leopard' colour. Is there any way to validate colous and not add the div if the color is not a valid background colour?

Damon
  • 3,004
  • 7
  • 24
  • 28
MJQ
  • 1,778
  • 6
  • 34
  • 60

3 Answers3

1

I would absolutely avoid using named colours (eg. red, white, etc...) while using instead the standard hex declaration, eg:

#FF0000 = #F00 = red
#000000 = #000 = black
#ffffff = #fff = white
#ac25B1 = some other *unnamed* colour

This way, you could easily check that the string is a valid HEX string, either 6 or 3 character long.

LittleSweetSeas
  • 6,786
  • 2
  • 21
  • 26
1

Make a list from the W3 Specifications.

Then check to see if your color is in that list. Here is an example.

colors = ['lime', 'orange', 'pink'];

if (colors.indexOf(the_color) >= 0) {
    // Set background
}
Dan Grahn
  • 9,044
  • 4
  • 37
  • 74
1

I think you could re-use this question's solution.

It involves a jQuery script that checks if the submitted color really produces RGB values. I'm copy-pasting it.

colorToTest = 'lime'; // 'lightgray' does not work for IE

$('#dummy').css('backgroundColor', 'white');
$('#dummy').css('backgroundColor', colorToTest);
if ($('#dummy').css('backgroundColor') != 'rgb(255, 255, 255)' || colorToTest == 'white') {
    alert(colorToTest+' is valid');
}

Here's how it works: First, the colorToTest variable is set to the color you wish to validate; Then, the background of the target div (#dummy in this case) is set to white via jQuery; At last, the background of the target div is set to colorToTest. If the color is still white, and colorToTest is not White, the backend color is not valid.

However, since an unvalid color won't produce any layout, you could just set the div background to white and then apply the backend color. If it's vaild, it will change. You could however use the above script to validate it, if you wish.

Community
  • 1
  • 1
Vereos
  • 503
  • 4
  • 15
  • Yes that can be a solution too. But I think while adding the divs if i compare the color to be in valid list, then add the div otherwise no! That will be better in my situation. Thanks for you suggastion. upvoted! – MJQ Dec 09 '13 at 17:07
  • Hm... you could set the div's `visibility` to `collapse` by default. If the color is valid, change it to `visible`. – Vereos Dec 09 '13 at 17:11