From 6ac8c667fbf3cfdb8f1bbe4d58076348be921655 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonathan=20Gonz=C3=A1lez=20Benavides?= <47956254+JonathanGzzBen@users.noreply.github.com> Date: Wed, 9 Oct 2024 10:03:29 -0600 Subject: [PATCH] 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> --- book/chapters/validators.md | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/book/chapters/validators.md b/book/chapters/validators.md index fffa38c7..f4f03c7c 100644 --- a/book/chapters/validators.md +++ b/book/chapters/validators.md @@ -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