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
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.
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.
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)
.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With