Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check String is valid hex color code in android

Tags:

java

android


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

like image 451
Android_programmer_office Avatar asked Apr 18 '14 14:04

Android_programmer_office


People also ask

How do you check if a string is a valid hex color?

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.

Is Hex valid?

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.

How do I know my hex color?

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).


1 Answers

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.

like image 90
njzk2 Avatar answered Oct 09 '22 19:10

njzk2