GibboK
GibboK

Reputation: 73918

What is you favourite approach to check if a HTML COLOR is valid?

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:

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;
            }
        }

Upvotes: 8

Views: 9482

Answers (5)

Anders B
Anders B

Reputation: 31

The Main method

static void Main(string[] args)
{
    List<string> testColors = new List<string>
    {
        null
        ,""
        ,"#00"
        ,"#000"
        ,"#12345aa"
        ,"#fff1az"
        ,"#FFDFD991"
        ,"ajdoajsdoijsaod"
    };

    foreach (var color in testColors)
    {
        bool result = IsHtmlColor(color);
        Console.WriteLine($"IsHtmlColor({color}) => {result}");
    }

}

The helper method

public static bool IsHtmlColor(string hexa)
{
    try
    {
        // using System.Windows.Media;
        return ColorConverter.ConvertFromString(hexa) is Color;
    }
    catch
    {
        return false;
    }
}

Upvotes: 1

FrancescoMM
FrancescoMM

Reputation: 2960

One regex for all, just for the fun. The i at the end is 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

Upvotes: 3

Abdullah-Al-Nahian
Abdullah-Al-Nahian

Reputation: 147

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
}

Upvotes: 2

Sameer Alibhai
Sameer Alibhai

Reputation: 3178

Exception handling is heavy and should be used as a last resort and only for actual exceptions. Try this. It checks for a valid html hex color and then tries named colors.

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;
}

Upvotes: 17

Quentin
Quentin

Reputation: 943569

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.

Upvotes: 8

Related Questions