Regular Expressions 101

Community Patterns

Validate hex color

4

Regular Expression
PCRE (PHP <7.3)

/
^#?([0-9a-f]{6}|[0-9a-f]{3})$
/
i

Description

Validates hexadecimal color codes based on the following rule set:

  • Optionally starting with a hash.
  • 3 or 6 characters in length.
  • Using the [0-9a-f] character set.
Submitted by Nathaniel Blackburn - 8 years ago