Hex Color Validation

Validate CSS hexadecimal color codes in both 3-digit and 6-digit formats.

BeginnerDesign
Regular Expression Pattern
^#([A-Fa-f0-9]6|[A-Fa-f0-9]3)$

Pattern Breakdown:

  • ^ - Start of string
  • # - Hash symbol (required)
  • ([A-Fa-f0-9]6|[A-Fa-f0-9]3) - Either 6 or 3 hex digits
  • [A-Fa-f0-9] - Hex digits (0-9, A-F, a-f)
  • $ - End of string

Supported Formats:

  • • 6-digit format: #RRGGBB (e.g., #FF5733)
  • • 3-digit format: #RGB (e.g., #F53)
  • • Case insensitive: Both uppercase and lowercase letters allowed
Live Hex Color Tester
Common Color Examples
Red
#FF0000
rgb(255, 0, 0)
Green
#00FF00
rgb(0, 255, 0)
Blue
#0000FF
rgb(0, 0, 255)
Yellow
#FFFF00
rgb(255, 255, 0)
Magenta
#FF00FF
rgb(255, 0, 255)
Cyan
#00FFFF
rgb(0, 255, 255)
Black
#000000
rgb(0, 0, 0)
White
#FFFFFF
rgb(255, 255, 255)
Implementation Examples
// Hex color validation regex
const hexColorRegex = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;

function validateHexColor(color) {
  return hexColorRegex.test(color);
}

// Usage examples
console.log(validateHexColor("#FF5733")); // true
console.log(validateHexColor("#3498db")); // true
console.log(validateHexColor("#000")); // true
console.log(validateHexColor("#FFF")); // true
console.log(validateHexColor("FF5733")); // false (missing #)
console.log(validateHexColor("#GG5733")); // false (invalid characters)
Test Cases
"#FF5733"

6-digit hex color (uppercase)

Valid
"#3498db"

6-digit hex color (lowercase)

Valid
"#000000"

6-digit black color

Valid
"#FFFFFF"

6-digit white color

Valid
"#000"

3-digit black color

Valid
"#FFF"

3-digit white color

Valid
"#f0f"

3-digit mixed case

Valid
"FF5733"

Missing # symbol

Invalid
"#GG5733"

Invalid characters (G)

Invalid
"#12345"

Invalid length (5 digits)

Invalid
"#1234567"

Invalid length (7 digits)

Invalid
"##FF5733"

Double # symbol

Invalid

Share & Save

Share this regex pattern with others or save it to your favorites