Checking for correct html JS color codes
2 answers
You can match hex colors as follows:
if (/^#[0-9a-f]{3}([0-9a-f]{3})?$/i.test(str)) {
//Match
}
Note that this does not handle names or rgb(n, n, n)
.
You can match colors rgb(x, y, z)
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
}
Please note that this will match rgb(299, 299, 299)
.
+3
a source to share
You can create an abstract element and try to apply 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 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;
}
+2
a source to share