Hex Color Code Validation Regex

Validate hex color codes in CSS format. Matches both 3-digit (#F57) and 6-digit (#FF5733) formats.

Pattern & Test String

About This Pattern

Pattern: ^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$

Flags: g

Results

Enter a regex pattern to see the results here.

Frequently Asked Questions

Does this match colors with or without the # symbol?

Yes, the # is optional with this pattern. To require it, remove the ? after #. To reject it, remove #? entirely.

What's the difference between 3 and 6 digit hex colors?

3-digit hex is shorthand where each digit is doubled. #F57 expands to #FF5577. Both formats are valid CSS.

Does this validate if the color will display correctly?

This only validates format. All syntactically correct hex codes are valid colors, though they may not look as expected.

Practical Examples

CSS Color Validation

Validate hex color input in style editors or design tools.

Color Picker Integration

Validate user-entered colors before applying to elements.

Theme Configuration

Validate color values in theme customization forms.

Common Issues & Solutions

This pattern is case-insensitive for a-f. CSS accepts both #FF5733 and #ff5733.

For strict 6-digit validation only, use: ^#?[a-fA-F0-9]{6}$

To extract RGB values, you'll need additional parsing after regex validation.