Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

validating html color codes JS

Tags:

javascript

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

like image 424
Utku Dalmaz Avatar asked May 12 '10 14:05

Utku Dalmaz


People also ask

How do I identify a color in HTML?

Colors are coded as red, green and blue intensities in hexadecimal notation (see hex chart). The first two characters represent the values 0 through 255 for red in hex; the middle two for green and the last two for blue (RRGGBB). For example, FF is equal to 255.

What are valid colors in HTML?

The World Wide Web Consortium (W3C) has listed 16 valid color names for HTML and CSS: aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, purple, red, silver, teal, white, and yellow.


2 Answers

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

like image 172
SLaks Avatar answered Sep 21 '22 16:09

SLaks


You could create an abstract element and attempt to apply the color to that element:

function validate_color(c) {
    var litmus = 'red';
    var d = document.createElement('div');
    d.style.color=litmus;
    d.style.color=c;
    //Element's style.color will be reverted to litmus or set to '' if an invalid color is given
    if( c !== litmus && (d.style.color === litmus || d.style.color === '')){
        return false;
    }
    return true;
}
like image 23
JayB Avatar answered Sep 22 '22 16:09

JayB