dotnet / command-line-api

Command line parsing, invocation, and rendering of terminal output.
https://github.com/dotnet/command-line-api/wiki
MIT License
3.38k stars 380 forks source link

Add a standard validator for range #769

Closed KathleenDollard closed 3 years ago

KathleenDollard commented 4 years ago

I'd like to be able to add a validator for a range (upper/lower bound for the value). I made a stab at this, but ran into a couple of issues:

I wonder if as a strongly typed parser, we need to have a set of validators that run before and after conversion. In addition to the range challenge, I can imagine cases where there are equivalent values that appear as different strings (1.0 vs 1.00).

If we don't want range as a standard validator, it would be nice to at least have guidance about how to write one.

amis92 commented 4 years ago

I'd just like to add that I've hit it as well - a need of validation of an already parsed/converted value. Of course, it's a simple workaround to just parse manually for validation, but as said above, it might be a common enough scenario.

Specifically, I had an argument of type Uri, but it's required to be UriKind.Absolute, so I had to parse and throw away result. If I could validate an Uri value, I could just check Uri.IsAbsoluteUri.

jonsequitur commented 4 years ago

If we think the new ParseArgument<T> delegate has the right shape and capabilities, it might be that we can just change the existing validators to run after conversion and receive T rather than the tokens.

dtv42 commented 4 years ago

I have implemented a set of Option extensions for validation and ease of use. They allow to write statements such as:

AddOption(new Option<int>  ("-d", "default value").Name("Number").Default(1));

or

AddOption(new Option<int>  ("-r", "range value [0..10]").Name("Number").Range(0, 10));

I also use this for validation for IPAddress, IPEndpoint, Uri or regular expressions. It is fairly simple but helps.