Pregunta

I have developed a C# solution which requires that the user can customize the format of a real number that is displayed, with a caption, a number and an unit.

I allowed the user to specify a format string that exactly matches the first parameter of a string.Format(), so he can tune the display the way he wants.

For example, {0}: {1:0.00} [{2}] will display Flow rate: 123.32 [Nm³/h].

The users knows how to use this formatting feature, that {0} is the caption, {1} is the number and {2} is the digit, and have the required minimal knowledge about .NET formatting.

However, at some point I have to validate the format string he entered, and I did not find other way than to use it against dummy values and to catch a FormatException this way:

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

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

    // entry rejection...
}

When an error happens, this is not the most user-friendly...

Could NET format strings be validated a more elegant way? Is there a way to provide some hints to the user in case of failure?

¿Fue útil?

Solución

There is most likely a much better and more efficient way to do this out there. This is just one possible way.

But Here is what I came Up with.

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

Here Is The Fiddle: http://dotnetfiddle.net/3wxU7R

Otros consejos

Have you tried:

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

// entry rejection...
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top