Skip to content

Commit

Permalink
Update transform validators documentation (#689)
Browse files Browse the repository at this point in the history
Close #688 
Adds an example on how to use transform validator objects and clarifies
the usage of the return type of the base function.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
JonathanGzzBen and pre-commit-ci[bot] authored Oct 9, 2024
1 parent f865d2b commit 6ac8c66
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions book/chapters/validators.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,27 @@ There are two forms of validators:
mutated)

A transform validator comes in one form, a function with the signature
`std::string(std::string)`. The function will take a string and return the
modified version of the string. If there is an error, the function should throw
a `CLI::ValidationError` with the appropriate reason as a message.
`std::string(std::string&)`. The function will take a string and return an error
message, or an empty string if input is valid. If there is an error, the
function should throw a `CLI::ValidationError` with the appropriate reason as a
message.

An example of a mutating validator:

```cpp
auto transform_validator = CLI::Validator(
[](std::string &input) {
if (input == "error") {
return "error is not a valid value";
} else if (input == "unexpected") {
throw CLI::ValidationError{"Unexpected error"};
}
input = "new string";
return "";
}, "VALIDATOR DESCRIPTION", "Validator name");

cli_global.add_option("option")->transform(transform_validator);
```
However, `check` validators come in two forms; either a simple function with the
const version of the above signature, `std::string(const std::string &)`, or a
Expand Down

0 comments on commit 6ac8c66

Please sign in to comment.