Sometimes, we want to check if string is valid CSS color with JavaScript.
In this article, we’ll look at how to check if string is valid CSS color with JavaScript.
How to check if string is valid CSS color with JavaScript?
To check if string is valid CSS color with JavaScript, we can use the CSS.supports
method.
For instance, we write:
const isRedValid = CSS.supports('color', 'red')
console.log(isRedValid)
const isRandomValid = CSS.supports('color', 'random')
console.log(isRandomValid)
to call CSS.supports
with the CSS property and the value respectively.
We call it to check if 'red'
is a valid CSS color property value with:
const isRedValid = CSS.supports('color', 'red')
Likewise, we call it to check if 'random'
is a valid CSS color property value with:
const isRandomValid = CSS.supports('color', 'random')
Therefore, isRedValid
is true
and isRandomValid
is false
.
Conclusion
To check if string is valid CSS color with JavaScript, we can use the CSS.supports
method.