Positional and Custom Arguments

Validation of positional arguments can be specified using the Args field
of Command.

The following validators are built in:

  • NoArgs - the command will report an error if there are any positional args.
  • ArbitraryArgs - the command will accept any args.
  • OnlyValidArgs - the command will report an error if there are any positional args that are not in the ValidArgs field of Command.
  • MinimumNArgs(int) - the command will report an error if there are not at least N positional args.
  • MaximumNArgs(int) - the command will report an error if there are more than N positional args.
  • ExactArgs(int) - the command will report an error if there are not exactly N positional args.
  • ExactValidArgs(int) - the command will report an error if there are not exactly N positional args OR if there are any positional args that are not in the ValidArgs field of Command
  • RangeArgs(min, max) - the command will report an error if the number of args is not between the minimum and maximum number of expected args.

An example of setting the custom validator:

  1. var cmd = &cobra.Command{
  2. Short: "hello",
  3. Args: func(cmd *cobra.Command, args []string) error {
  4. if len(args) < 1 {
  5. return errors.New("requires a color argument")
  6. }
  7. if myapp.IsValidColor(args[0]) {
  8. return nil
  9. }
  10. return fmt.Errorf("invalid color specified: %s", args[0])
  11. },
  12. Run: func(cmd *cobra.Command, args []string) {
  13. fmt.Println("Hello, World!")
  14. },
  15. }