什么是你最喜欢的方法来检查,如果一个HTML颜色是有效的? [英] What is you favourite approach to check if a HTML COLOR is valid?

查看:211
本文介绍了什么是你最喜欢的方法来检查,如果一个HTML颜色是有效的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用C#和ASP.NET 4器WebControls。

我有一个文本框我的网页上,用户可以输入HTML颜色以十六进制格式(FF0000)或HTML格式(红楼梦)。

我最初的想法是,这将是太难写一个正则表达式能够验证这个用户的输入,所以我想出了一个主意,写一个简单的方法来检查,如果输入的颜色可以转化为一个有效的被使用System.Drawing中的上下文

下面我code。它返回一个布尔数据类型说明,如果操作成功。
它工作正常现在,但我想知道:


  • 如果我的方法写得很好?

  • 你知道一个更好的办法?

感谢您的考虑。

 使用SD = System.Drawing中;保护静态布尔CheckValidFormatHtmlColor(字符串inputColor)
        {
            尝试
            {
                SD.Color myColor = SD.ColorTranslator.FromHtml(inputColor);
                返回true;
            }
            赶上(异常前)
            {
                返回false;
            }
        }


解决方案

我的直觉说,不信任微软的时候,它会得到类似的HTML颜色code正确。我发现这似乎是<一个href=\"http://reflector.webtropy.com/default.aspx/DotNET/DotNET/8@0/untmp/whidbey/REDBITS/ndp/fx/src/CommonUI/System/Drawing/Advanced/ColorTranslator@cs/1/ColorTranslator@cs\"相对=nofollow>来源$ C ​​$ C到类你正在使用它接受了很多的东西不是HTML颜色。

一个正则表达式,然后检查对清单听起来像这种前进是明智的。

修剪白色空间后,检查它是否符合 / ^#[A-FA-F0-9] {6} $ / ,如果没有,比较它的出现在HTML 16种颜色列表。

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.

这篇关于什么是你最喜欢的方法来检查,如果一个HTML颜色是有效的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆