Skip to content

Is it possible to control the order of an option validations? #1823

@TPIvan

Description

@TPIvan

Let's have a root command with one int16 option

    var root = new RootCommand("Root command description");
    var tstopt = new Option<Int16>("-t", "testing int16 option");
    root.AddOption(tstopt);

If I use not numeric value I am getting an error as expected

Cannot parse argument 'hh' for option '-t' as expected type 'System.Int16'.

But when I add a validator

   root.AddValidator((result) =>
   {
       if (string.IsNullOrEmpty(result.ErrorMessage) && result.GetValueForOption(tstopt) == 3)
       { result.ErrorMessage = "cannot be 3"; }
   });

I am getting an exception

Unhandled exception. System.InvalidOperationException: Cannot parse argument 'hh' for option '-t' as expected type 'System.Int16'.
   at System.CommandLine.Binding.ArgumentConverter.GetValueOrDefault[T](ArgumentConversionResult result)
   at System.CommandLine.Parsing.OptionResult.GetValueOrDefault[T]()
   at System.CommandLine.Parsing.SymbolResult.GetValueForOption[T](Option`1 option)
   at Program.<>c__DisplayClass0_0.<<Main>$>b__0(CommandResult result) in C:\MyDiskArea\LiveProgProjects\IVAN_TEST\TechnologyTesting\System.CommandLine\ConsoleApp73\Program.cs:line 10
   at System.CommandLine.Parsing.ParseResultVisitor.UseValidators(Command command, CommandResult innermostCommandResult)
   at System.CommandLine.Parsing.ParseResultVisitor.ValidateCommandResult()
   at System.CommandLine.Parsing.ParseResultVisitor.Stop()
   at System.CommandLine.Parsing.ParseResultVisitor.Visit(SyntaxNode node)
   at System.CommandLine.Parsing.Parser.Parse(IReadOnlyList`1 arguments, String rawInput)
   at System.CommandLine.Parsing.ParserExtensions.InvokeAsync(Parser parser, String[] args, IConsole console)
   at Program.<Main>$(String[] args) in C:\MyDiskArea\LiveProgProjects\IVAN_TEST\TechnologyTesting\System.CommandLine\ConsoleApp73\Program.cs:line 19
   at Program.<Main>(String[] args)

So it seems that the custom validatio is runnin before built it ones.
Is it possible to change the behavior?

Metadata

Metadata

Assignees

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions