how to check if a color is valid in javascript

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:


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:


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.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe