Easy way to check FormatString is valid?

谁说胖子不能爱 提交于 2019-12-12 21:14:35

问题


Is there an easy way to check if a format string is valid? For example the following is code that we use to test a number format string;

public static bool IsValidFormatStringNumber(string FormatString)
{
    try
    {
        const decimal number = 0.056m;
        var formattedNumber = number.ToString(FormatString);
        return formattedNumber.Length > 0;
    }
    catch
    {
        return false;
    }
}

We're trying to catch an exception or determine if the resulting string has no length. This test fails however as a format string of "hsibbur" (Any rubbish) results in a string of "hsaibbur", which has length.

We want to do the same test for Percent and Date format string.


回答1:


If you just want to check for standard format strings, just check that your format strings are part of that list.

If you want to check for custom format strings (that are not "Other" or "Literal strings"), you can probably craft a regex to do it.

Other than that, since format strings can be arbitrary strings, I don't think validation even applies.




回答2:


If FormatString is equal to formattedNumber, that could be another case for returning false.



来源:https://stackoverflow.com/questions/7974597/easy-way-to-check-formatstring-is-valid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!