Checking for correct html JS color codes

I am looking for some code to check html color codes. want to check if the user has typed in the correct color code, can you help guyz?

I know I need this regex, but I can't figure out what regex is: S

thanks

+2


a source to share


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


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







All Articles