Skip to content

isCssColor

Checks whether a value is a syntactically-safe, plain CSS color: a hex color (#rgb, #rgba, #rrggbb, #rrggbbaa), a functional notation (rgb(), rgba(), hsl(), hsla()), or a single-word named color (red, rebeccapurple).

Intended to sanitize a color value before interpolating it into inline style/cssText — it does not implement the full CSS color grammar or validate named colors against the real keyword list, it only rejects characters ({, }, ;, “) or shapes that could smuggle extra CSS declarations into the surrounding rule.

Available since next

import { isCssColor } from '@helpers4/guard';
isCssColor(value: unknown): value is string
ParameterTypeDescription
valueunknownThe value to check

value is string — true if value is a string that looks like a safe, plain CSS color

Validate a color before writing it to inline style

Section titled “Validate a color before writing it to inline style”

Accepts hex, functional (rgb/rgba/hsl/hsla), and named colors.

isCssColor('#ff0000')            // => true
isCssColor('rgba(0, 0, 0, 0.5)') // => true
isCssColor('rebeccapurple')      // => true
isCssColor(42)                   // => false

Reject values that could inject extra CSS declarations

Section titled “Reject values that could inject extra CSS declarations”

Guards against untrusted data smuggling a second declaration into a style attribute.

isCssColor('red; background: url(evil)') // => false
isCssColor('red}body{color:blue')        // => false

View source on GitHub