regexValidHexColor top-level constant

String const regexValidHexColor

Validates hex color strings in various formats (CSS-style or 0x prefixed).

Supported formats (with optional # or 0x prefix):

  • 3 digits: RGB → #RGB / 0xRGB (e.g., #123 → #112233)
  • 4 digits: RGBA → #RGBA / 0xRGBA (e.g., 0x1234 → #11223344)
  • 6 digits: RRGGBB → #FF00FF / 0xFF00FF
  • 8 digits: RRGGBBAA → #FF00FF80 / 0xFF00FF80

Examples:

  • Valid: "#123", "0xabc", "#FF00FF", "0x80808080", "a1b"
  • Invalid: "12", "0x12345", "#ghijk", "0xXYZ"

NOTE: This regex is case-sensitive by default (only 0x prefix and lowercase hex digits match without flags). For case-insensitive matching:

RegExp(
  regexValidHexColor,
  caseSensitive: false,
).hasMatch('0XFF00ff'); // true (uppercase prefix + mixed case)

Implementation

const String regexValidHexColor =
    r'^(?:0x|#)?(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$';