![]() |
CLI11 2.7.1
C++11 Command Line Interface Parser
|
There are two forms of validators:
A transform validator comes in one form, a function with the signature std::string(std::string&). The function will take a string and return an error message, or an empty string if input is valid. Alternatively, the function may throw a CLI::ValidationError with the appropriate reason as a message; either returning a non-empty string or throwing signals a failure, so throwing is not required.
An example of a mutating 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 subclass of struct CLI::Validator. This structure has two members that a user should set; one (func_) is the function to add to the Option (exactly matching the above function signature, since it will become that function), and the other is name_, and is the type name to set on the Option (unless empty, in which case the typename will be left unchanged).
Validators can be combined with & and |, and inverted with !. They have an operator() so that you can call them as if they were a function. In CLI11, const static versions of the validators are provided so that the user does not have to call a constructor also.
An example of a custom validator:
If you were not interested in the extra features of Validator, you could simply pass the lambda function above to the ->check() method of Option.
The built-in validators for CLI11 are:
| Validator | Description |
|---|---|
| ExistingFile | Check for existing file (returns error message if check fails) |
| ExistingDirectory | Check for an existing directory (returns error message if check fails) |
| ExistingPath | Check for an existing path |
| NonexistentPath | Check for an non-existing path |
| Range(min=0, max) | Produce a range (factory). Min and max are inclusive. |
| NonNegativeNumber | Range(0,max<double>) |
| PositiveNumber | Range(denorm_min<double>,max<double>), i.e. any positive number |
A few built-in transformers are also available
| Transformer | Description |
|---|---|
| EscapedString | modify a string using defined escape characters |
| FileOnDefaultPath | Modify a path if the file is a particular default location |
And, the protected members that you can set when you make your own are:
| Type | Member | Description |
|---|---|---|
| std::function<std::string(std::string &)> | func_ | Core validation function - modifies input and returns "" if successful |
| std::function<std::string()> | desc_function_ | Optional description function (returns an empty string if not set) |
| std::string | name_ | The name for search purposes |
| int (-1) | application_index_ | The element this validator applies to (-1 for all) |
| bool (true) | active_ | This can be disabled |
| bool (false) | non_modifying_ | Specify that this is a Validator instead of a Transformer |
Until CLI11 v3.0 these validators will be available by default. They can be disabled at compilation time by defining CLI11_DISABLE_EXTRA_VALIDATORS to 1. After version 3.0 they can be enabled by defining CLI11_ENABLE_EXTRA_VALIDATORS to 1. Some of the Validators are template heavy so if they are not needed and compilation time is a concern they can be disabled.
| Validator | Description |
|---|---|
| ValidIPV4 | check for valid IPV4 address XX.XX.XX.XX |
| TypeValidator<T> | template for checking that a value can convert to a specific type |
| Number | Check that a value can convert to a number |
| IsMember | Check that a value is one of a set of values |
| CheckedTransformer | Values must be one of the transformed set or the result |
| AsNumberWithUnit | checks for numbers with a unit as part of a specified set of units |
| AsSizeValue | As Number with Unit with support for SI prefixes |
| Transformer | Description |
|---|---|
| Bound(min, max) or Bound(max) | Force a range (factory). Min and max are inclusive; min defaults to 0. |
| Transformer | Modify values in a set to the matching pair value |
Some additional validators can be enabled by using CLI11_ENABLE_EXTRA_VALIDATORS to 1. These validators are disabled by default. They also require <filesystem> support (C++17, CLI11_HAS_FILESYSTEM).
| Validator | Description |
|---|---|
| ReadPermissions | Ensure a file or directory has permissions to read the file |
| WritePermissions | Ensure a file or directory has write permissions |
| ExecPermissions | Ensure a file has exec permissions |
| NonEmptyFile | Ensure that a file exists and is not empty |
| FileSizeValidator | specify that the size must be between min and max sizes |
IsMember restricts a value to a set. Pass any iterable container with a ::value_type, or a copyable pointer to one, or an initializer list:
After the set you can pass "filter" functions of the form T(T), which are applied before the comparison. CLI::ignore_case, CLI::ignore_underscore, and CLI::ignore_space are provided:
Transformer and CheckedTransformer map one value to another. They take containers of pairs, so a map is the usual choice:
Transformer passes values that are not in the map through unchanged. CheckedTransformer requires the value to match either a key or one of the expected outputs, and raises a ValidationError if it does not. A Transformer used with check does nothing, since check may not modify the value.
If you pass a shared pointer to the container instead of the container itself, you can change the contents later, and the help text and the check both follow the current contents:
TransformPairs<T> is an alias for std::vector<std::pair<std::string, T>> for the same use with the transformers. If the container has a find function, like std::map, that function does the search; otherwise the search is linear. With filters present, the fast search runs first and a filtered linear search is the fallback.
A Validator is a copyable object with settings you can change. Every one of these functions returns a reference to the Validator, so they chain:
| Operation | Effect |
|---|---|
| .description(text) | Replace the description shown in the help. |
| .name(text) | Name the Validator, so it can be found later with get_validator(name). |
| .active(bool) | Turn the Validator on or off. |
| .application_index(int) | Apply only to one element of the result. Zero based; a negative index applies to all values. |
| .operation(func) | Replace the validation function. |
The application index is what makes validation of compound types work. For a std::pair<int, std::string> where the first element must be positive and the second must be a file:
A named Validator can be found and changed after the option is built, which is how you turn a check on or off at runtime:
get_validator(name) throws CLI::OptionNotFound if there is no match. With no name, or an empty name, it returns the first unnamed Validator, or the only one if there is just one. get_validator(index) takes the position in the applied order instead, and returns nullptr for an invalid index.
For reading the current state there are get_description(), get_name(), get_active(), get_application_index(), and get_modifying(), which is true when the Validator may change the value. Modification is controlled by non_modifying(), but it is better to let check and transform set it.
CLI11 also supports the use of custom validators, this includes using the Validator class constructor with a custom function calls or subclassing Validator to define a new class.
The simplest way to make a new Validator is to mimic how many of the existing Validators are created. Take for example the IPV4Validator
The IPV4Validator class inherits from Validator and creates a new constructor. In that constructor it defines the lambda function that does the checking. Then IPV4 can be used like any other Validator. One specific item of note is that the class does not define any new member variables, so the class if copyable to a Validator, only the constructor is different.
If additional members are needed, then the check and transform overloads that use shared pointers need to be used. The other overloads pass by value so polymorphism doesn't work. The custom_validator example shows a case like this.
The Validator defines some new operations, and in the use case the Validator is constructed using shared_ptrs. This allows polymorphism to work and the Validator instance to be shared across multiple options, and as in this example adapted during the parsing and checking.
There are a few limitation in this, single instances should not be used with both transform and check. Check modifies some flags in the Validator to prevent value modification, so that would prevent its use as a transform. Which could be user modified later but that would potentially allow the check to modify the value unintentionally.