I wanted to add a manual hexadecimal input for a C# repository of mine, I had no way of verifying if the user's input was a legitimate ARGB hexadecimal value the user had entered into the textbox or if it was a garbage hexadecimal number. Does anyone have a potential solution to this?
Asked
Active
Viewed 330 times
2
-
2https://stackoverflow.com/a/25933687/251311 ? – zerkms Jul 01 '20 at 05:35
-
What UI framework are you working with? – Zohar Peled Jul 01 '20 at 05:35
-
.net Framework 4.8 – Virtualization Jul 01 '20 at 06:05
-
Note that the input doesn't just needs to be a hex number, it also needs to be a valid ARGB value. So it must be exactly 8 chars long, unless you want to support a default value for the A (FFFFFF = opaque white) and/or "single digit bytes" (FFF = white) – Hans Kesting Jul 01 '20 at 06:43
-
What if the user was to input a non valid ARGB value such as #GGGGGG? – Virtualization Jul 01 '20 at 07:21
-
Since it's user input validation, it doesn't have to be performant. How this string is used afterwards? I guess you have a method which takes such string as an input. You can simply run this method inside `try/catch` to see if it works. – Sinatr Jul 01 '20 at 07:38
-
1https://stackoverflow.com/q/2109756/10216583 – Jul 01 '20 at 09:11
-
Does this answer your question? [How do I get the color from a hexadecimal color code using .NET?](https://stackoverflow.com/questions/2109756/how-do-i-get-the-color-from-a-hexadecimal-color-code-using-net) – bvpb Jul 01 '20 at 22:07
2 Answers
3
You can just use regex:
string pattern = @"^0[xX][0-9a-f]{8}$";
string input = "0x1a2b3C";
Match m = Regex.Match(input, pattern, RegexOptions.IgnoreCase);
if (m.Success)
{...}

Zze
- 18,229
- 13
- 85
- 118
-
81. the `0x` prefix is a c# thing, I doubt the users will use that. 2. If you're already going with `RegexOptions.IgnoreCase`, there's no point of using `a-fA-F` in the pattern as well. 3. I think the `\g` here is not needed. Instead, you should use `^` at the beginning and `$` at the end, to indicate that the entire string should match the regular expression. 4. argb values are 8 digits long - so instead of `+` you should use `{8}`. – Zohar Peled Jul 01 '20 at 05:42
-1
So, I did a very inefficient method, I started off by making a pastebin with every single valid ARGB hex code, I then wrote the following:
WebClient Checker = new WebClient();
string List = Checker.Downloadstring("https://pastebin.com/raw/link");//link would be the pastebin
string Input = this.TextBox.Text;
if (List.Contains(Input))
{
//submit write file code here
}
else
{
System.Windows.Messagebox.Show("The Input Was Not Valid! Please Input A Valid ARGB Code!", "Error!");
}
This method ended up working for me. It isn't recommended but does the job right.

Virtualization
- 29
- 5