validation
Hex Color Code Regex Pattern
Validates a CSS hex color code — either 3-digit shorthand (#F53) or full 6-digit (#FF5733). Accepts both upper and lower case hex digits. Does not match 8-digit RGBA hex.
/^#([0-9a-fA-F]{3}){1,2}$/ What each part matches
^# — required leading hash([0-9a-fA-F]{3}) — one group of 3 hex digits{1,2}$ — one or two of those groups (3 or 6 total digits)✓ These match
- #FF5733
- #F53
- #000000
- #fff
✗ These don't
- FF5733
- #GG5733
- #FF573
- #FF573399
Use in your code
JavaScript
const re = /^#([0-9a-fA-F]{3}){1,2}$/;
re.test(input); // → true or false Python
import re
re.fullmatch(r"^#([0-9a-fA-F]{3}){1,2}$", input) PHP (PCRE)
preg_match('/^#([0-9a-fA-F]{3}){1,2}$/', $input); Go
re := regexp.MustCompile(`^#([0-9a-fA-F]{3}){1,2}$`)
re.MatchString(input) FAQ
Does this hex color code regex work in JavaScript?
Yes. Every pattern in the Utilko regex library is tested to work in JavaScript RegExp, PCRE (PHP, Nginx), and Python `re`. Where flavor matters (lookbehind, named groups), the pattern page flags it.
How do I use this pattern?
Copy the pattern from the code block above. In JavaScript:
new RegExp('^#([0-9a-fA-F]{3}){1,2}$') or literal /^#([0-9a-fA-F]{3}){1,2}$/. Or click "Try in regex tester" to open it pre-loaded in Utilko's browser-based regex tester.Should I use this for security-critical validation?
Client-side regex is fine for UX (immediate feedback on a form). For anything security-critical — payments, auth, data integrity — always re-validate server-side using the same pattern PLUS domain-specific checks (Luhn checksum for cards, actual email delivery test, DNS resolution for domains).