tags:

views:

22

answers:

1

hi,

i am looking for code to validate html color codes. wanna check if user typed valid color code, can you guyz help ?

i know i need that regex stuff but i cant understand a think about that regex things :S

thanks

+1  A: 

You can match hexadecimal colors like this:

if (/^#[0-9a-f]{3}([0-9a-f]{3})?$/i.test(str)) {
    //Match
}

Note that this wont handle names or rgb(n, n, n).

You can match rgb(x, y, z) colors like this:

if (/^rgb\s*(\s*[012]?[0-9]{1,2}\s*,\s*[012]?[0-9]{1,2}\s*,\s*[012]?[0-9]{1,2}\s*)$/i.test(str)) {
    //Match
}

Note that this will match rgb(299, 299, 299).

SLaks
It will handle #aaa which, while being a perfectly good CSS colour code is (like rgb()) not a valid HTML colour code.
David Dorward
?? 3-digit color codes are definitely valid. They mean the same as 6-digit codes, where the second digit of each color part is "0".
Pointy
Note: you need to have a (?:) grouping around that second block (turning the string into `if (/^#[0-9a-f]{3}(?:[0-9a-f]{3})?$/i.test(str))` - otherwise, color codes like `#aba` won't match.
ABach
@ABach: `#aba` matches fine.
SLaks
@SLaks: when I put your regex test (`/^#[0-9a-f]{3}[0-9a-f]{3}?$/i.test('#aba');`) into Chrome's Javascript console, it returns false. *EDIT:* it also returns false in Firefox's JS console.
ABach
@ABach: I already added a capturing group a while ago.
SLaks