Forum Moderators: open

Message Too Old, No Replies

Checking for valid hex colors

using javascript

         

mattglet

8:19 pm on Nov 17, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I'm trying to build a hex color checker that actually knows what the hex colors are.

i.e.

function fncIsValidColor(hexcolor) {
var strPattern = /^([0-9a-f]{1,2}){3}$/i;
return strPattern.test(hexcolor);
}

That's a simple RegEx to check for valid characters, and will validate if you pass in AFAFAF. AFAFAF is not a valid hex color. If you do something like:
document.forms['myform'].inputbox.style.backgroundColor = '#AFAFAF';

You'll get an "Invalid property" error, because it's not a valid color. Is there anything to help me, or even a way to suppress the error message?

Lance

8:54 pm on Nov 17, 2004 (gmt 0)

10+ Year Member



You may have something else going on there because #afafaf is a valid color. It's a medium grey.

moltar

9:11 pm on Nov 17, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Any color is valid starting from 000000 to FFFFFF.

The error is probably somewhere else. Maybe your form name is incorrect?

Bernard Marx

9:28 pm on Nov 17, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Variations:

- accept only strings with '#'

/^[blue]#[/blue]([0-9a-f]{1,2}){3}$/i

- '#' is optional

/^[blue]#?[/blue]([0-9a-f]{1,2}){3}$/i

Strictly, of course, strings without '#' are invalid. Probably only accepted by IE these days.

Lance is right. If you get an error with:

document.forms['myform'].inputbox.style.backgroundColor = '#AFAFAF';

..there's something fishy going on. It's fine.

-------------------------------------------

To 'hide' errors:

window.onerror = function(){ return true; }

or you could put individual statements in a try..catch block.

mattglet

10:18 pm on Nov 17, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



<edit> Got it. Thanks everyone for the help!</edit>

Lance

10:56 pm on Nov 17, 2004 (gmt 0)

10+ Year Member



Sure thing...

But what was it?

(For completeness, and because I'm dying to know) ;)

mattglet

3:10 am on Nov 18, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



On every keystroke I was checking the input value for valid color codes. If a valid color is entered, I would change the color of a "sample swatch".

I was having a problem because I was setting the background color to invalid codes (i.e. .style.backgroundColor = 'a';). So it would error on me. I had to change it so instead of setting the background color after every keystroke, I validate the color first against some code that generates all the hex codes. So now, if the input value doesn't validate first, the background color doesn't get set, therefore no more errors.

Thanks again for the help.

rkolsky

10:32 pm on Nov 24, 2004 (gmt 0)

10+ Year Member



Just a thought but this regex could have a possible flaw. This will validate either a 3 digit or 6 digit hex code. This does not cause an error in IE. It just assumes that zero's come first. I just wanted to point it out because it could have unexpected results depending on what you use it for.

Bernard Marx

9:13 am on Nov 25, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Interesting. Could you elaborate a little?

rkolsky

5:13 pm on Nov 25, 2004 (gmt 0)

10+ Year Member



Sure, The posted regex is /^#([0-9a-f]{1,2}){3}$/

This says repeat any of the characters from 0-9 or a-f at least once but no more than twice. Then it says repeat the last grouped expression 3 times. So since the previous expression can be 1 or 2 this could mean that it would validate at 3,4,5, or 6 characters. I know i said 3 or 6 in my last post but I didn't think it all the way through. it could be between 3 and 6 characters. To validate only 6 characters try this

/^#[0-9a-f]{6}$/i

Bernard Marx

5:25 pm on Nov 25, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Well pointed out.
But don't you mean:

/^#[0-9a-f]{3,6}$/i

to allow for #abc, which is valid too.

How would you go about checking for good ol' websafe colours?

Bernard Marx

7:43 pm on Nov 25, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



How about this ugly beast?

reg = /^#[0-9a-f]{3}$¦^#([0-9a-f])\1([0-9a-f])\2([0-9a-f])\3$/i

str1 = "#aabb3c" // no
str2 = "#aabbcc" // yes

alert(reg.test(str1))
alert(reg.test(str2))

PhoenixMan

5:09 am on Nov 26, 2004 (gmt 0)

10+ Year Member



That "ugly beast", at least in AOL's IE, returns every hex' code false, even when I entered in three other web safe colors.

Bernard Marx

9:05 am on Nov 26, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You'll need to change the broken pipe ¦ symbol first
(see: [webmasterworld.com ])

tracyfu

6:32 am on Dec 1, 2004 (gmt 0)

10+ Year Member



Hi. I'm a newbie to reg exps and I couldn't get Bernard's reg exp to work for me. I did replace the broken pipe. I don't really understand the '\1', '\2', and '\3' syntax in the expression (Please explain?).

I'm actually making a color picker for a project of mine too. This expression worked for me:

strPattern = /^([0-9a-f]{3}){1,2}$/i;

I'm just checking for a 3 or 6 char hex and changing the swatch on a valid test.

This thread was timed perfectly cause I've been going nuts for the last few hours. :)

Bernard Marx

10:47 am on Dec 1, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



If you want to save a couple of chars, then this should do the same.
Any valid hex string (no #):

/^[0-9a-f]{3,6}$/i

The longer one is more complicated, of course, because it's testing for 'websafe' colours.
Those of the form: #aabbcc, or the shortened form, #abc .

Why doesn't it work for you?

That confuses me. It works fine at this end.
Remember that the expression only accepts strings that begin with #.

Have a go again, with the # characters removed from the expression.

My expression is probably brute force over ignorance, and I'm out a on limb. It has two parts, separated by our pipe. The expression will accept a string that passes either part.

1. Test for #abc

^#[0-9a-f]{3}$

..simple enough

2. Test for #aabbcc

^#([0-9a-f])\1([0-9a-f])\2([0-9a-f])\3$

I don't know how to say "..and followed by exactly that character again". The way round it was to use groups. The first two characters are represented by..

([0-9a-f])\1

The first char '[0-9a-f]' is wrapped in parentheses. You can refer to groups formed in this way via

/n
, where
n
is the order of appearance of the group in the expression. I formed 3 groups. One for each first char of a pair.

In this case, each group is referred to immediately afterwards, so the effect is:

"a valid char, followed by itself again" * 3

tracyfu

6:35 pm on Dec 1, 2004 (gmt 0)

10+ Year Member



I get it now :). I looked up regex back-referencing after reading your explanation. Thanks for your help. I got it to work this morning—not sure what changed. I recopied the pattern and it worked fine.

Thanks again.