What is your favorite approach to check if HTML COLOR really matters?

I am using C # and ASP.NET 4 WebControls.

I have a TextBox on my page. The user can enter the HTML color in HEXADECIMAL format (ff0000) or in HTML format ("Red").

My initial thought was that it would be too difficult to write RegEx capable of checking this user input, so I came up with the idea of ​​writing a simple method to check if the input color can be converted to a valid one, which the System.Drawing context will use.

Below is my code. It returns a Bool DataType indicating whether the operation was successful. Now it works fine, but I would like to know:

  • If my method was well written?
  • Do you know a better approach?

Thank you for your attention.

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;
            }
        }
+5
4

, Microsoft, HTML. , , , , HTML.

, , .

, /^#[a-fA-F0-9]{6}$/, , 16 , HTML.

+7

. . html hex .

protected static bool CheckValidFormatHtmlColor(string inputColor)
{
       //regex from http://stackoverflow.com/a/1636354/2343
       if (Regex.Match(inputColor, "^#(?:[0-9a-fA-F]{3}){1,2}$").Success)
           return true;

       var result = System.Drawing.Color.FromName(inputColor);
       return result.IsKnownColor;
}
+6

One regex for everyone, just for fun. I am at the end - for case insensitivity. Probably not fast, but "one shot."

HTML colors

/^(#[a-f0-9]{6}|black|green|silver|gray|olive|white|yellow|maroon|navy|red|blue|purple|teal|fuchsia|aqua)$/i

CSS colors

/^(#[a-f0-9]{6}|#[a-f0-9]{3}|(rgb|hsl) *\( *[0-9]{1,3}%? *, *[0-9]{1,3}%? *, *[0-9]{1,3}%? *\)|(rgba|hsla) *\( *[0-9]{1,3}%? *, *[0-9]{1,3}%? *, *[0-9]{1,3}%? *, *[0-9]{1,3}%? *\)|black|green|silver|gray|olive|white|yellow|maroon|navy|red|blue|purple|teal|fuchsia|aqua)$/i
+3
source
using System.Text.RegularExpressions;

var regexColorCode = new Regex("^#[a-fA-F0-9]{6}$");
string colorCode = "#FFFF00";

if (!regexColorCode.IsMatch(colorCode.Trim()))
{   
    ScriptManager.RegisterStartupScript(this, GetType(), "showalert" ,"alert('Enter a valid Color Code');", true);
}
else
{
    //do your thing
}
+1
source

All Articles