Skip to content

Commit

Permalink
Merge pull request #1544 from dearchap/issue_786
Browse files Browse the repository at this point in the history
Documentation:(issue_786) Add docs for flag validation
  • Loading branch information
dearchap authored Oct 25, 2022
2 parents 7732a51 + de73d1b commit 7563894
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions docs/v2/examples/flags.md
Original file line number Diff line number Diff line change
Expand Up @@ -596,3 +596,53 @@ The precedence for flag value sources is as follows (highest to lowest):
0. Environment variable (if specified)
0. Configuration file (if specified)
0. Default defined on the flag

#### Flag Actions

Handlers can be registered per flag which are triggered after a flag has been processed.
This can be used for a variety of purposes, one of which is flag validation

<!-- {
"args": ["&#45;&#45;port","70000"],
"error": "Flag port value 70000 out of range[0-65535]"
} -->
```go
package main

import (
"log"
"os"
"fmt"

"github.com/urfave/cli/v2"
)

func main() {
app := &cli.App{
Flags: []cli.Flag{
&cli.IntFlag{
Name: "port",
Usage: "Use a randomized port",
Value: 0,
DefaultText: "random",
Action: func(ctx *cli.Context, v int) error {
if v >= 65536 {
return fmt.Errorf("Flag port value %v out of range[0-65535]", v)
}
return nil
},
},
},
}

if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
}
```

Will result in help output like:

```
Flag port value 70000 out of range[0-65535]
```

0 comments on commit 7563894

Please sign in to comment.