Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you validate a composite format string in C# against its target argument types?

Given a composite format string provided by the user (for use with String.Format) and a set of types representing the arguments that would be used to format the composite format string, how can you check that the user-provided value is valid?

It should be pretty easy to create a regular expression to check that the general syntax of the argument placeholders match "{index[,alignment][:formatString]}" per the documentation. And not too much more difficult to verify that the indexes of the placeholders in the composite format string are less than the actual number of typed arguments (i.e. they don't reference an argument that won't be given). However, given the types for the arguments that will be passed in are known, it should also be possible to validate the ":formatString" is appropriate for those types.

For example, you want to validate the user doesn't specify "{0:dddd MMMM}" as a format string when the first argument type (0 index) is a number (String.Format("{0:dddd MMMM}", 1234) yields "dddd MMMM"). The quantity of ":formatString" options by type is too large to want to manually check everything. Is there any other way? Or do you just have to live with the user potentially specifying a bad format string?

Assume there are no custom IFormatProvider, ICustomFormatter or IFormattable implementations in play here. Just basic types already in the .NET Framework. Bonus points for addressing the custom stuff.

like image 624
iammichael Avatar asked Dec 30 '22 02:12

iammichael


1 Answers

There is no inbuilt way of doing this, AFAIK.

You could code every common case manually, but I don't recommend it.

(edit) One pragmatic option might be try/catch - test the format as early as possible when the user enters it....

like image 92
Marc Gravell Avatar answered Jan 01 '23 16:01

Marc Gravell