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
The color black with hexadecimal color code #000000 / #000 is a very dark shade of gray. In the RGB color model #000000 is comprised of 0% red, 0% green and 0% blue. In the HSL color space #000000 has a hue of 0° (degrees), 0% saturation and 0% lightness.
The color white with hexadecimal color code #ffffff / #fff is a very light shade of gray. In the RGB color model #ffffff is comprised of 100% red, 100% green and 100% blue. In the HSL color space #ffffff has a hue of 0° (degrees), 0% saturation and 100% lightness.
Note: This is strictly for validation, i.e. accepting a valid hex color. For actual parsing you won't get the individual parts out of this.
^#(?:[0-9a-fA-F]{3}){1,2}$
For ARGB:
^#(?:[0-9a-fA-F]{3,4}){1,2}$
Dissection:
^ anchor for start of string # the literal # ( start of group ?: indicate a non-capturing group that doesn't generate backreferences [0-9a-fA-F] hexadecimal digit {3} three times ) end of group {1,2} repeat either once or twice $ anchor for end of string
This will match an arbitrary hexadecimal color value that can be used in CSS, such as #91bf4a
or #f13
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With