I use C# and ASP.NET 4 WebControls.
I have a TextBox on my page, User can input a HTML Color in HEXADECIMAL format (ff0000) or in HTML Format (“Red”).
My initial thought was that would be too difficult writing a RegEx able to validate this User’s input, so I come up with an idea to write a simple method to check if the inputted color can be translated to a valid one to be used the context of System.Drawing.
Below my code. It returns a Bool DataType stating if the operation was successful.
It is working fine for now but I would like to know:
- If my method was well written?
- Do you know a better approach?
Thanks for your consideration.
using SD = System.Drawing;
protected static bool CheckValidFormatHtmlColor(string inputColor)
{
try
{
SD.Color myColor = SD.ColorTranslator.FromHtml(inputColor);
return true;
}
catch (Exception ex)
{
return false;
}
}
My gut says to mistrust Microsoft when it comes to getting something like an HTML colour code right. I’ve found what appears to be the source code to the class you are using and it accepts a lot of things that are not HTML colours.
A regex then checking against a list sounds like the sensible way forward for this.
After trimming white space, check if it matches
/^#[a-fA-F0-9]{6}$/, if it doesn’t, compare it to the list of 16 colours that appear in HTML.