Check if string is a valid CSS color expression?

Viewed 311

If I have a string that is a CSS code to be used as a color, Is it possible to check the value validity?

What i want is:

A function or a regex to validate if inputted code is a valid CSS code where it returns true when the value is a CSS function as linear-gradient, color names as red, hex, rgb, hsl colors or initial, inherit, currentColor, transparent values, and returns false otherwise.

Like:

check('linear-gradient(140deg, rgba(0, 0, 0, 1) 0%, rgba(85, 85, 85, 1) 89%, rgba(153, 153, 153, 1) 100%)'); // should return true
check('#abcdzzff') // should return false
check('aquamarin') // should also return false (missing e)

Thanks.

1 Answers

Since @StefanWang doesn't want to post his answer, I shall post it myself.

I credit this to him, thank you stefan.

let validate = c => {
    let img = document.createElement('img');
    img.style = 'background: rgb(0, 0, 0)';
    img.style = 'background: ' + c;
    if (img.style.background != 'rgb(0, 0, 0)' && img.style.background != '') return true;
    img.style = 'background: rgb(255, 255, 255)';
    img.style = 'background: ' + c;
    return (img.style.background != 'rgb(255, 255, 255)' && img.style.background != '');
}

console.log(validate('transparent')); // true
console.log(validate('hsl(30, 60%, 90%)')); // true
console.log(validate('linear-gradient(140deg, #000 0%, #666 90%, #ccc 100%)')); // true
console.log(validate('red')); // true
console.log(validate('#000')); // true
console.log(validate('#zzz')); // false

Related