Skip to main content
AllDevToolsHub
Back to all patterns

Hexadecimal Color Validation

Validation

Validates 3-digit and 6-digit hex color codes.

/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/

How it works

This pattern matches a string that starts with a hash # followed by either exactly 3 or exactly 6 hexadecimal characters (0-9, a-f, A-F).

Test Cases

Should Match

  • #fff
  • #000000
  • #FF5733

Should NOT Match

  • #1234
  • fff
  • #GHIJKL

Quick Summary

Validates CSS hex color codes in both shorthand (#RGB) and full (#RRGGBB) formats. Does not match 8-digit RGBA hex (#RRGGBBAA), extend the alternation if needed.

Key Takeaways

Key Takeaways

  • Matches both 3-digit (#RGB) and 6-digit (#RRGGBB) hex colors
  • Case-insensitive for hex digits (A-F and a-f both valid)
  • Requires the leading #, strip it first if your input omits it
  • Does not match 8-digit RGBA hex (#RRGGBBAA) used in CSS Color Level 4
Use Cases

When to use it

  • Validating color picker inputs in design tools
  • Parsing CSS files to extract color values
  • Sanitizing user-submitted theme configuration
Watch out

Common Mistakes

  • Not accounting for 8-digit RGBA hex colors (#RRGGBBAA) in modern CSS
  • Forgetting that CSS also accepts rgb(), hsl(), and named colors, hex validation alone is insufficient for full CSS color validation
FAQ

Hexadecimal Color Validation, Frequently Asked

How do I match 8-digit RGBA hex colors too?

Extend the alternation: ^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$

Is #FFF the same as #FFFFFF?

Yes. CSS expands 3-digit shorthand by doubling each digit: #FFF → #FFFFFF, #ABC → #AABBCC.