Color Validator

Validate CSS colors in JS


import validate from "color-validator"

validate.color("#DC143C") // true
validate.keyword("#DC143C") // false
validate.hex("#DC143C") // true
validate.hexAlpha("#DC143C") // false
validate.oklch("#DC143C") // false
validate.oklch("oklch(40.1% 0.123 21.57)") // false
    

While working on another project I needed a way to check whether some text was a valid CSS color. I was working with a variety of colors, including oklch. I couldn't find anything that included oklch in their validations.

"Just a little regex should do," I thought. I ended up going down a rabbit hole of all the variations for each type of CSS color: named, hex, rgb, hsl, lch, etc. This was the product of that rabbit hole.

Looking at just hsl, there are a bunch of valid patterns.


// with commas
hsl(0, 0%, 0%);
hsl(0, 0%, 0%, 25%) // with alpha
hsl(0, 0%, 0%, .25) // alpha as decimal
hsl(20deg, 0%, 0%, 0.25) // hue as degree
hsl(.2turn, 0%, 0%, 0.25) // hue as decimal turn

// without commas
hsl(0 0% 0%)
hsl(0 0% 0% / 25%)
hsl(0 0% 0% / .25) 
hsl(20deg 0% 0% / 0.25)
hsl(.2turn 0% 0% / 0.25)
hsl(20 100% 100% / 1)

// hsla
hsla(0, 0%, 0%, 25%) // hsla
hsla(0, 0%, 0%, .25)
hsla(20 0% 0% / 0.25)
hsla(.2turn 0% 0% / 0.25)
    

At the heart of the the validation are a handful of regex fragments that can be used to construct most of the color formats.


const decimal = `(?:\.\d+)`;
const zeroToOne = `(?:0|0?(${decimal})|1)`;
const zeroToNine = `[0-9]${decimal}?`;
const oneToNine = `[1-9]${decimal}?`;
...
    

Interestingly, as I was finishing things up I ran across the validate-color library. It turns out it is very similar to what I had originally looked for (still without oklch though). And it's solution to the many similar, but slightly different patterns, was pretty much the same as mine. I guess there is nothing new under the sun.