Skip to content

How to add constraints to an int option? #905

Open

Description

@loudenvier

Is it possible to set constraints to an int option so that it have min and max allowed values? I think that's a pretty common scenario, but the following fails:

[Option('q', "quality", Default = 80, Min = 1, Max = 100)]
public int Quality { get; set; }    

With this exception: System.InvalidOperationException: Scalar option specifications do not support range specification.

If the library does not provide this functionality how would I implement it on my own and still play nicely with the auto help and error messages that the library automatically outputs on invalid input?

Activity

  1. changed the title [-]How to validate an int option?[/-] [+]How to add constraints to an int option?[/+] on Nov 2, 2023
  2. ShadowXPA commented on Aug 19, 2025

    @ShadowXPA

    As per the wiki, the Min and Max only apply to IEnumerable.

    I agree, it's a pretty common scenario, and I tried doing the same you did.
    My work around is validating the options manually, and displaying an error message, along with the help text. It would be nice to have an option to add errors to the list of errors though, so it shows in the help text.

    I have this Extension method:

    public static HelpText AddErrors(this HelpText helpText, IEnumerable<string> errors)
    {
        helpText.AddPreOptionsLine("\nERROR(S):"); // Simulating the ERROR(S)'s header
        helpText.AddPreOptionsLines(errors); // You might want to format your errors by prefixing with 2 spaces to match the original
        return helpText;
    }
    

    Something like this would be nicer:

    var helpText = HelpText.AutoBuild(parserResult);
    helpText.AddErrorLine("Quality needs to be between 1 and 100.");
    // helpText.AddErrorLines(["", "", ...]);
    // helpText.AddErrorText("");
    Console.WriteLine(helpText);
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions