Function to see if Hex color is valid?

  • Thread starter Thread starter Mark B
  • Start date Start date
M

Mark B

I'd like a function to inspect a string to see if it is a valid Hexadecimal
color:

fIsValidHexColor(strHex) as Boolean

Anyone come across this before?
 
Mark B said:
I'd like a function to inspect a string to see if it is a valid
Hexadecimal color:

fIsValidHexColor(strHex) as Boolean

Anyone come across this before?


Doesn't it just need to be true that the string can be parsed to an int? If
so, this works:

bool TestString(string s)
{
int argb;
if (int.TryParse(s, System.Globalization.NumberStyles.HexNumber, null, out
argb))
return true;
else return false;
}
 
I'd like a function to inspect a string to see if it is a valid Hexadecimal
color:

fIsValidHexColor(strHex) as Boolean

Anyone come across this before?

The answer depends on what format the string is in.

If it is just the hex digits, then you can try to parse as a
hexadecimal number into an Integer and make sure the result is >= 0
and <= &HFFFFFF.

If the string will have some sort of hex identifier (leading &H,
leading 0x, etc.) you will also need to check for that.

Also, you might or might not want to force the string to have at least
5 hex digits or maybe even require 6.
 
Back
Top