Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

isValidHexColor

Checks whether a string is a valid hexadecimal color code.

TypeScript
Copied!
1/**
2 * Checks whether a string is a valid hexadecimal color code.
3 *
4 * @param str - The string to validate.
5 * @returns True if the string is a valid hex color, false otherwise.
6 */
7export function isValidHexColor(str: string): boolean {
8  return /^#(?:[0-9a-fA-F]{3}){1,2}$/.test(str);
9}
  • Compact and Fast

    Uses a single, efficient regular expression to validate both short (#abc) and long (#aabbcc) hex color formats.

  • Case-Insensitive Matching

    Supports both uppercase and lowercase hex digits without any additional processing.

  • Strict Format Enforcement

    Ensures the string starts with # and contains exactly 3 or 6 valid hexadecimal digits — nothing more, nothing less.

  • No External Dependencies

    Lightweight, self-contained function suitable for browser or Node.js environments.

Tests | Examples

TypeScript
Copied!
1test('validates 3-digit hex colors', () => {
2  expect(isValidHexColor('#fff')).toBe(true);
3  expect(isValidHexColor('#123')).toBe(true);
4});
5
6test('validates 6-digit hex colors', () => {
7  expect(isValidHexColor('#ffffff')).toBe(true);
8  expect(isValidHexColor('#ABCDEF')).toBe(true);
9});
10
11test('invalidates incorrect hex colors', () => {
12  expect(isValidHexColor('fff')).toBe(false);
13  expect(isValidHexColor('#ffff')).toBe(false);
14  expect(isValidHexColor('#12345g')).toBe(false);
15  expect(isValidHexColor('#12')).toBe(false);
16  expect(isValidHexColor('#')).toBe(false);
17});
18
19test('invalidates non-string values and empty string', () => {
20  expect(isValidHexColor('')).toBe(false);
21  expect(isValidHexColor('123456')).toBe(false);
22});

Common Use Cases

  • User Input Validation

    Validate color inputs in UI design tools, theming panels, or settings forms.

  • CSS Preprocessing

    Check and sanitize hex color codes before injecting them into stylesheets or inline styles.

  • Design System Enforcement

    Ensure that only valid hex colors are used in configuration files or design tokens.

  • Form Field Sanitization

    Prevent invalid or malformed color values from being submitted to back-end services.

  • Custom Theme Generators

    Verify and accept only valid hex colors in dynamic theme customization workflows.

Codebase: Utilities -> Validation -> isValidHexColor | Yevhen Klymentiev