【问题标题】:How to validate a .NET formatting string?如何验证 .NET 格式化字符串?
【发布时间】:2014-04-11 06:15:38
【问题描述】:

我开发了一个 C# 解决方案,要求用户可以自定义显示的实数格式,包括标题、数字和单位。

我允许用户指定与string.Format() 的第一个参数完全匹配的格式字符串,因此他可以按照自己的方式调整显示。

例如,{0}: {1:0.00} [{2}] 将显示Flow rate: 123.32 [Nm³/h]

用户知道如何使用此格式化功能,即 {0} 是标题,{1} 是数字,{2} 是数字,并且对 .NET 格式化具有所需的最低限度的知识。

但是,在某些时候,我必须验证他输入的格式字符串,除了将其用于虚拟值并以这种方式捕获 FormatException 之外,我没有找到其他方法:

try
{
    string.Format(userFormat, "", 0d, "");

    // entry acceptance...
}
catch(FormatException)
{
    messageBox.Show("The formatting string is wrong");

    // entry rejection...
}

发生错误时,这不是最人性化的...

能否以更优雅的方式验证 NET 格式字符串?有没有办法在失败时向用户提供一些提示?

【问题讨论】:

  • 你可以使用ErrorProvider Class
  • 试试看this SO question
  • @icemanind 哦,我错过了那个。有趣的是,接受的答案正是我想知道的问题。我可能想太多了,这可能是这个问题被否决的原因。

标签: c# validation string-formatting


【解决方案1】:

很可能有一种更好和更有效的方法来做到这一点。这只是一种可能的方式。

但这是我想出的。

public bool IsInputStringValid(string input)
    {
        //If there are no Braces then The String is vaild just useless
        if(!input.Any(x => x == '{' || x == '}')){return true;}

        //Check If There are the Same Number of Open Braces as Close Braces
        if(!(input.Count(x => x == '{') == input.Count(x => x == '}'))){return false;}

        //Check If Value Between Braces is Numeric

        var tempString = input; 

        while (tempString.Any(x => x == '{'))
        {
            tempString = tempString.Substring(tempString.IndexOf('{') + 1);
            string strnum = tempString.Substring(0, tempString.IndexOf('}'));

            int num = -1;
            if(!Int32.TryParse(strnum, out num))
            {
                    return false;
            }       
        }

        //Passes Validation
        return true;
    }

这是小提琴:http://dotnetfiddle.net/3wxU7R

【讨论】:

  • 所以,据我了解,没有任何神奇的方法可以做到这一点,而无需实现自己的验证逻辑并解析条目。感谢您花时间提出一个例子。你的答案值得被接受。
【解决方案2】:

你试过了吗:

catch(FormatException fe)
{
     messageBox.Show("The formatting string is wrong: " + fe.Message);

// entry rejection...
}

【讨论】:

  • 是的,很遗憾,90% 的时间都是“输入字符串格式不正确”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-25
  • 1970-01-01
  • 1970-01-01
  • 2022-08-15
  • 2021-06-20
  • 2011-11-28
相关资源
最近更新 更多