1
0
mirror of https://github.com/CLIUtils/CLI11.git synced 2025-05-03 14:03:52 +00:00

Update transform validators documentation (#689)

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>
This commit is contained in:
Jonathan González Benavides 2024-10-09 10:03:29 -06:00 committed by GitHub
parent f865d2b296
commit 6ac8c667fb
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -7,9 +7,27 @@ There are two forms of validators:
mutated) mutated)
A transform validator comes in one form, a function with the signature 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 `std::string(std::string&)`. The function will take a string and return an error
modified version of the string. If there is an error, the function should throw message, or an empty string if input is valid. If there is an error, the
a `CLI::ValidationError` with the appropriate reason as a message. 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 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 const version of the above signature, `std::string(const std::string &)`, or a