- Published on
Validate color
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 colorsisValidColor('purple') // trueisValidColor('burlywood') // trueisValidColor('lightsalmon') // trueisValidColor('rgb(255, 255, 255)') // trueisValidColor('rgba(255, 255, 255, .5)') // trueisValidColor('#ccc') // trueisValidColor('hsl(100, 0%, 18%)') // true
// Invalid colorsisValidColor('not-a-color-name') // falseisValidColor('dark gray') // false. Should be 'darkgray'isValidColor('rgb(255, 255, 255, 1, 1)') // falseisValidColor('#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)') // trueisValidColor('none') // falseisValidColor('initial') // falseisValidColor('gray') // true