Mengke's blog

Check if a string is a valid color

Published on
Published on
/
1 mins read
/
––– views

For client-side only, not work in Node.js

Simple color validator function

const isValidColor = (color) => {
  const otpNode = new Option()
  otpNode.style.color = color

  return !!otpNode.style.color
}

Usage

// 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:

const isValidColor = (color) => {
  const 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