Colore JS

Search documentation

Find a function or jump to a section.
v2.0.1

Handle invalid colors

A color field can contain an unfinished hex code, a typo or a CSS variable the parser cannot resolve. Choose how to handle that input based on what you need to tell the user.

Use a fallback while someone types

import { Color } from 'colore-js';

const value = Color.try('rgb(12)') ?? new Color('#2563eb');
console.log(value.css()); // '#2563eb'

Color.try() gives you a Color or null. It suits a live preview whose input can be incomplete for a keystroke or two.

Show a validation message

import { ColorError, parse } from 'colore-js';

try {
  parse('not-a-color');
} catch (error) {
  if (!(error instanceof ColorError)) throw error;
  console.log('Enter a supported CSS color.'); // 'Enter a supported CSS color.'
}

Use a stricter path when a form submits or a file imports. You can log the error’s message and show wording that fits the field. If only a boolean is needed, call isValidColor.

Detect the format after validation

import { detectFormat, isValidColor } from 'colore-js';

console.log(detectFormat('rgb(12)')); // 'rgb'
console.log(isValidColor('rgb(12)')); // false

A recognizable function name still needs valid channels. Treat detectFormat() as a label for an input you have already checked.