Skip to content
the poor coder

how to check if a color is valid in javascript

Poor Man
Published
Reading time
3 min read
On this page

How to Check if a Color is Valid in JavaScript#

As a web developer, you must have come across situations where you needed to validate a color value in JavaScript. To validate a color, you can use the RegExp object or CSS parser libraries like Parsel. Let's explore both methods in detail.

Method 1: Using RegExp#

A color in JavaScript can be represented in various formats such as RGB, Hex, HSL, etc. To validate a color using RegExp, you need to write a pattern that can match all the possible formats. Here's an example:

Text

const isValidColor = (color) => {
  const hexPattern = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;
  const rgbPattern = /^rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)$/;
  const rgbaPattern = /^rgba\((\d{1,3}),(\d{1,3}),(\d{1,3}),(\d{1}|0?\.\d+)\)$/;
  const hslPattern = /^hsl\((\d{1,3}),(\d{1,3})%,(\d{1,3})%\)$/;
  const hslaPattern = /^hsla\((\d{1,3}),(\d{1,3})%,(\d{1,3})%,(\d{1}|0?\.\d+)\)$/;

  return hexPattern.test(color)
    || rgbPattern.test(color)
    || rgbaPattern.test(color)
    || hslPattern.test(color)
    || hslaPattern.test(color);
};

// Usage
console.log(isValidColor('#fff')); // true
console.log(isValidColor('#123456')); // true
console.log(isValidColor('rgb(255, 255, 255)')); // true
console.log(isValidColor('rgba(0, 0, 0, 0.5)')); // true
console.log(isValidColor('hsl(0, 0%, 100%)')); // true
console.log(isValidColor('hsla(120, 60%, 70%, 0.5)')); // true
console.log(isValidColor('invalid-color')); // false

The above example uses regular expressions to match different color formats. If the input color matches any of the patterns, isValidColor will return true, otherwise, it will return false.

Method 2: Using Parsel#

Parsel is a lightweight CSS parser library that can parse any valid CSS color value. It has built-in validation for color values, so you don't have to worry about writing complex regular expressions. Here's how you can use Parsel to validate a color:

Text

import { parseCSS } from 'parsel';

const isValidColor = (color) => {
  try {
    const parsed = parseCSS(`color: ${color}`);
    const { type, value } = parsed[0].value;

    return type === 'color' && value !== 'transparent';
  } catch (err) {
    return false;
  }
};

// Usage
console.log(isValidColor('#fff')); // true
console.log(isValidColor('#123456')); // true
console.log(isValidColor('rgb(255, 255, 255)')); // true
console.log(isValidColor('rgba(0, 0, 0, 0.5)')); // true
console.log(isValidColor('hsl(0, 0%, 100%)')); // true
console.log(isValidColor('hsla(120, 60%, 70%, 0.5)')); // true
console.log(isValidColor('invalid-color')); // false

In this example, we use the parseCSS function to parse the input color and check if it's a valid color. Parsel returns an array of CSS properties, so we access the first property and check its type and value properties. If the type is color and the value is not transparent, we consider it a valid color.

Conclusion#

Validating colors in JavaScript is essential for ensuring that the user inputs a valid color value. You can use RegExp or libraries like Parsel to validate colors in different formats. Choose the method that suits your requirements and implement it in your project.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC