Leo's dev blog

Validate if a string is a valid color

Published on
Published on
/1 mins read/---

WARNING

This util is for client-side only, do not use it in Server environments.

Simple color validator function

utils.ts
export function isValidColor(color: string) {
  let otpNode = new Option()
  otpNode.style.color = color
 
  return !!otpNode.style.color
}

Usage

index.ts
// Valid colors
isValidColor('purple') // true
isValidColor('burlywood') // true
isValidColor('lightsalmon') // true
isValidColor('rgb(255, 255, 255)') // true
isValidColor('rgba(255, 255, 255, .5)') // true
isValidColor('#ccc') // true
isValidColor('hsl(100, 0%, 18%)') // true
 
// Invalid colors
isValidColor('not-a-color-name') // false
isValidColor('dark gray') // false. Should be 'darkgray'
isValidColor('rgb(255, 255, 255, 1, 1)') // false
isValidColor('#ccczzz') // false

Caveat

Strings like unset, initial, inherit, currentcolor, transparent are also valid values, so if you want to exclude these strings, just change the function a bit:

utils.ts
export function isValidColor(color: string) {
  let otpNode = new Option()
  otpNode.style.color = color
 
  return !!otpNode.style.color && !/(unset|initial|inherit|currentcolor|transparent)/i.test(color)
}
 
isValidColor('rgb(-1, 255, 255)') // true
isValidColor('none') // false
isValidColor('initial') // false
isValidColor('gray') // true