Replies: 3 comments
-
Give |
Beta Was this translation helpful? Give feedback.
-
Thank for the suggestion. I've used Frankly, I would be fine with my solution doing it in the command action, if there was a way to report an error like validators or custom parsers, but I don't think that's possible. |
Beta Was this translation helpful? Give feedback.
-
Found the solution! Validators provide the same access to options as in the action callback, but also provide the var startDateOption = new Option<DateOnly>("--start-date") {
Description = "Start date for evaluation",
DefaultValueFactory = _ => DateOnly.Parse("2018-01-01")
};
var endDateOption = new Option<DateOnly>("--end-date") {
Description = "End date for evaluation",
DefaultValueFactory = _ => DateOnly.Parse("2022-12-31")
};
var rootCommand = new RootCommand("root") {
startDateOption,
endDateOption
};
rootCommand.Validators.Add(parseResult => {
var startDate = parseResult.GetValue(startDateOption);
var endDate = parseResult.GetValue(endDateOption);
if(startDate > endDate) {
parseResult.AddError($"{startDateOption.Name} must be before {endDateOption.Name}");
}
});
rootCommand.SetAction(parseResult => {
var startDate = parseResult.GetValue(startDateOption);
var endDate = parseResult.GetValue(endDateOption);
// do work
return 0;
} |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I know how to validate individual options, but I have a use case where I have 2 options that need to be validated together.
Take the following example where the command takes 2 dates. Each date option has a default value when omitted. The command needs to make sure that the dates are valid with each other.
How do I do that?
I have tried using a validator on the command, but it appears to be executed before the options are parsed, so I don't have access to the value created by
DefaultValueFactory
.The above code is the best approximation I have, but I don't see a way to generate a validation error that late in the execution flow when inside the action handler.
Beta Was this translation helpful? Give feedback.
All reactions