Hex Color Validator API: Validate Hex Color Codes

Need to validate user-submitted color codes? This guide covers the Hex Color Validator API, which validates hex color formats, normalizes different representations, and converts valid colors to multiple formats.

Hex Color Formats

Hex colors can be written in several formats:

  • 6-digit with #: #RRGGBB (e.g., #3498db)
  • 6-digit without #: RRGGBB (e.g., 3498db)
  • 3-digit shorthand: #RGB (e.g., #F00 = #FF0000)
  • 8-digit with alpha: #RRGGBBAA (e.g., #3498db80)
  • 4-digit shorthand: #RGBA (e.g., #F008 = #FF000088)

Validation Rules

A valid hex color must:

  • Contain only hexadecimal characters (0-9, A-F, a-f)
  • Be exactly 3, 4, 6, or 8 characters (excluding #)
  • Optionally start with # symbol
Note: The API normalizes all valid inputs to standard 6-digit format (#RRGGBB) while preserving alpha if present.

Using the Hex Validator API

TinyFn provides an endpoint for hex color validation:

API Request
GET https://api.tinyfn.io/v1/color/validate-hex
Headers: X-API-Key: your-api-key
Response (Valid)
{
  "input": "#3498db",
  "valid": true,
  "normalized": "#3498db",
  "formats": {
    "hex": "#3498db",
    "hex_no_hash": "3498db",
    "rgb": "rgb(52, 152, 219)",
    "rgb_values": { "r": 52, "g": 152, "b": 219 },
    "hsl": "hsl(204, 70%, 53%)",
    "hsl_values": { "h": 204, "s": 70, "l": 53 }
  },
  "has_alpha": false
}
Response (Invalid)
{
  "input": "#GGG",
  "valid": false,
  "error": "Invalid hex color format",
  "hint": "Hex colors must contain only 0-9 and A-F characters"
}

Parameters

Parameter Type Description
color string Hex color string to validate (required)
require_hash boolean Require # prefix. Default: false
allow_shorthand boolean Allow 3/4 digit shorthand. Default: true
allow_alpha boolean Allow 8-digit alpha format. Default: true

Code Examples

JavaScript / Node.js

// Validate user input
async function validateColor(userInput) {
  const response = await fetch(
    'https://api.tinyfn.io/v1/color/validate-hex?' + new URLSearchParams({
      color: userInput
    }),
    { headers: { 'X-API-Key': 'your-api-key' } }
  );
  const result = await response.json();

  if (result.valid) {
    console.log(`Valid! Normalized: ${result.normalized}`);
    console.log(`RGB: ${result.formats.rgb}`);
  } else {
    console.log(`Invalid: ${result.error}`);
  }
}

validateColor('#F00');  // Valid - shorthand for #FF0000
validateColor('3498db'); // Valid - missing # is OK
validateColor('#GGG');  // Invalid - not hex characters

Python

import requests

def validate_hex(color_input):
    response = requests.get(
        'https://api.tinyfn.io/v1/color/validate-hex',
        params={'color': color_input},
        headers={'X-API-Key': 'your-api-key'}
    )
    result = response.json()

    if result['valid']:
        print(f"Valid: {result['normalized']}")
        print(f"RGB: {result['formats']['rgb']}")
    else:
        print(f"Invalid: {result['error']}")

validate_hex('#3498db80')  # Valid with alpha
validate_hex('ABC')  # Valid shorthand
validate_hex('12345')  # Invalid - wrong length

cURL

curl "https://api.tinyfn.io/v1/color/validate-hex?color=%233498db" \
  -H "X-API-Key: your-api-key"

Common Use Cases

  • Form Validation: Validate color picker or text inputs
  • Data Import: Validate colors during data import
  • API Validation: Validate color parameters in API requests
  • Normalization: Standardize color formats across a system
  • Color Conversion: Get RGB/HSL equivalents of hex colors

Best Practices

  1. Trim whitespace: Remove whitespace before validation
  2. Be flexible: Accept colors with or without # prefix
  3. Normalize storage: Store colors in a consistent format
  4. Provide feedback: Show helpful error messages for invalid input

Use via MCP

Your AI agent can call this tool directly via Model Context Protocol — no HTTP code needed. Add TinyFn to Claude Desktop, Cursor, or any MCP client:

{
  "mcpServers": {
    "tinyfn-color": {
      "url": "https://api.tinyfn.io/mcp/color/",
      "headers": {
        "X-API-Key": "your-api-key"
      }
    }
  }
}

See all color tools available via MCP in our Color MCP Tools for AI Agents guide.

Try the Hex Color Validator API

Get your free API key and start validating hex colors.

Get Free API Key

Ready to try TinyFn?

Get your free API key and start building in minutes.

Get Free API Key