Hex Color Code Validation Regular Expression
Hex color codes are widely used in CSS, design tools, and UI configuration files to represent colors with hexadecimal digits. This pattern validates the two most common formats: three-digit shorthand like#fff and six-digit full values like #1A2B3C. It requires the leading hash symbol and accepts uppercase or lowercase hexadecimal characters. An alpha-capable variant is also included below for interfaces that store transparency directly in the color value while still accepting the regular 3-digit and 6-digit forms.
Recommended Solution
Explanation
^#- Start of the string followed by a required#.(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})- Matches either exactly 3 or exactly 6 hexadecimal digits.[0-9a-fA-F]- A single hexadecimal digit: 0-9, a-f, or A-F.$- End of the string.
Notes
- This pattern validates format only. It does not normalize the value or convert shorthand colors like
#abcinto#aabbcc. - The recommended pattern intentionally excludes alpha channels. Use the alternative pattern below when you want to accept
#RRGGBBAAin addition to the regular 3-digit and 6-digit forms. - If you also accept named CSS colors like
redor functional formats likergb(255, 0, 0), validate those separately rather than weakening this regex. - Hex colors commonly appear in style systems alongside token names and other configuration values.
Implementation
Test Cases
| Hex Color | Valid |
|---|---|
| #000 | |
| #fff | |
| #1a2 | |
| #1A2B3C | |
| #abcdef | |
| #ABCDEF | |
| #123456 | |
| 123456 | |
| #12 | |
| #1234 | |
| #12345 | |
| #1234567 | |
| #GGG | |
| #12G45F | |
| #abcdex | |
| #fff | |
| #fff | |
| (empty string) |
Hex With Optional Alpha
If your system supports transparency in hex notation, use a pattern that accepts #RRGGBBAAin addition to standard #RGB and #RRGGBB values.
Explanation
^#- Start of the string followed by a required#.(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})- Matches 3-digit shorthand, 6-digit full hex, or 8-digit hex with alpha.$- End of the string.
Note: This alternative is useful when the same input can contain standard hex colors or alpha-enabled values. It still rejects unsupported lengths such as 4-digit shorthand.
Implementation
Test Cases
| Hex Color With Optional Alpha | Valid |
|---|---|
| #000 | |
| #fff | |
| #123456 | |
| #00000000 | |
| #FFFFFFFF | |
| #1A2B3C7F | |
| #abcdef99 | |
| #123456FF | |
| #12 | |
| #1234 | |
| #1234567 | |
| #123456789 | |
| #GGGGGGGG | |
| #GGG | |
| #12G45F99 | |
| #00000000 | |
| #00000000 | |
| (empty string) |