I\'m looking for a regular expression to validate hex colors in ASP.NET C# and
am also looking code for validation on server side.
For instance: #CCCCCC
This should match any #rgb
, #rgba
, #rrggbb
, and #rrggbbaa
syntax:
/^#(?:(?:[\da-f]{3}){1,2}|(?:[\da-f]{4}){1,2})$/i
break down:
^ // start of line
# // literal pound sign, followed by
(?: // either:
(?: // a non-capturing group of:
[\da-f]{3} // exactly 3 of: a single digit or a letter 'a'–'f'
){1,2} // repeated exactly 1 or 2 times
| // or:
(?: // a non-capturing group of:
[\da-f]{4} // exactly 4 of: a single digit or a letter 'a'–'f'
){1,2} // repeated exactly 1 or 2 times
)
$ // end of line
i // ignore case (let 'A'–'F' match 'a'–'f')
Notice that the above is not equivalent to this syntax, which is incorrect:
/^#(?:[\da-f]{3,4}){1,2}$/i
This would allow a group of 3 followed by a group of 4, such as #1234567
, which is not a valid hex color.