---
heading: 'Color validator'
title: 'Validate if a string is a valid color'
date: '2021-10-12'
icon: 'Typescript'
draft: false
summary: 'Validate strings to ensure they represent valid colors in various formats (hex, RGB, and named colors).'
tags: ['typescript', 'color', 'validator']
---

> [!WARNING]
> This util is for client-side only, do not use it in Server environments.

Simple color validator function

```ts:utils.ts showLineNumbers
export function isValidColor(color: string) {
  let otpNode = new Option()
  otpNode.style.color = color

  return !!otpNode.style.color
}
```

Usage

```ts:index.ts showLineNumbers
// 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:

```ts:utils.ts showLineNumbers
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
```
