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
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
all answers mentioned RGB format, here is regex for ARGB format:
^#[0-9a-fA-F]{8}$|#[0-9a-fA-F]{6}$|#[0-9a-fA-F]{4}$|#[0-9a-fA-F]{3}$
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.
In Ruby, you have access to the \h (hexadecimal) character class. You also have to take more care of line endings, hence the \A...\z instead of the more common ^...$
/\A#(\h{3}){1,2}\z/
This will match 3 or 6 hexadecimal characters following a #. So no RGBA. It's also case-insensitive, despite not having the i flag.