paligap
paligap

Reputation: 942

Easy way to check FormatString is valid?

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.

Upvotes: 5

Views: 3006

Answers (2)

Jim Rhodes
Jim Rhodes

Reputation: 5085

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

Upvotes: 1

Jordão
Jordão

Reputation: 56477

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.

Upvotes: 5

Related Questions