I had a String which I need to validate whether it is valid hex color code or not .
My sample strings are as follows :
1 - #ff00000
2 -#ff347820
How to validate the above strings to check whether they are valid hex color codes or not .
Can anyone help me in sorting out this issue ?
Thanks in advance
The length of the hexadecimal color code should be either 6 or 3, excluding '#' symbol. For example: #abc, #ABC, #000, #FFF, #000000, #FF0000, #00FF00, #0000FF, #FFFFFF are all valid Hexadecimal color codes.
Yes, in hexadecimal, things like A, B, C, D, E, and F are considered numbers, not letters. That means that 200 is a perfectly valid hexadecimal number just as much as 2FA is also a valid hex number.
Hex color codes start with a pound sign or hashtag (#) and are followed by six letters and/or numbers. The first two letters/numbers refer to red, the next two refer to green, and the last two refer to blue. The color values are defined in values between 00 and FF (instead of from 0 to 255 in RGB).
The proper Android way of testing this, independently of supporting future formats, is to rely on the Color
class.
Like this:
try {
Color color = Color.parseColor(myColorString);
// color is a valid color
} catch (IllegalArgumentException iae) {
// This color string is not valid
}
As a bonus, it also supports named colors such as magenta
, blue
...
The main pro over regex matching is semantic. This code explicitly tests the myColorString
String against being a Color. You practically don't need any comment at all to tell what is does.
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