3

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.

  • 2
    If you are can access DOM (running on a browser), the best answer to your question seems https://stackoverflow.com/questions/6386090/validating-css-color-names – robdev91 Dec 21 '20 at 20:13
  • @StefanWang it works great for rgb hsl and others but it doesn't work for CSS function, do you happen to know another code for CSS functions? I'm fine with 2 functions. – user4378298 Dec 21 '20 at 20:20
  • @StefanWang so i kept messing around with that code and it works fine now if instead of writing `image.style.color` i write `image.style.background`. It wouldn't work for `rgb(0, 0, 0)` but you can easily write an if case for it. SO if you care, please write an answer so i can mark it, thanks. – user4378298 Dec 21 '20 at 20:43
  • You can use image.style – robdev91 Dec 21 '20 at 20:48
  • You mean [`CSS.supports`](https://developer.mozilla.org/en-US/docs/Web/API/CSS/supports)? – Sebastian Simon Dec 22 '20 at 01:38
  • 1
    Duplicate of [How to check if css value is supported by the browser?](https://stackoverflow.com/q/36191797/4642212). – Sebastian Simon Dec 22 '20 at 01:46

1 Answers1

-2

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