Skip to main content

Validation

Open this example when parse-time rejection matters more than keeping to the sugar aliases. It shows how to combine explicit conversion and validation actions in one pipeline.

This is the page to read when you want bad input to fail early, with clear errors, before the rest of your program starts running.

Source​

Source: examples/validation.cc

examples/validation.cc
#include <iostream>

#include "cli/argument.hh"
#include "cli/parser.hh"

struct Args {
cli::Description description{
"Validation-focused example covering range, regex, and filesystem "
"checks."};
cli::Help<> help;

cli::Arg<"port", 'p',
cli::conversion::integer<int> | cli::validation::range<1, 65535> |
cli::pack::set_once>
port{{.help = "TCP port number", .presence = cli::required}};

cli::Arg<"profile", cli::conversion::string |
cli::validation::matches<"[a-z][a-z0-9_-]*"> |
cli::pack::set_once>
profile{{.help = "Lowercase profile name", .presence = cli::required}};

cli::Arg<"output", 'o',
cli::conversion::path | cli::validation::parent_exists |
cli::pack::set_once>
output{{.help = "Output path whose parent must already exist"}};
};

auto main(int argc, char* argv[]) -> int {
const auto args = cli::parse_or_exit<Args>(argc, argv);

std::cout << "port: " << *args.port << '\n';
std::cout << "profile: " << *args.profile << '\n';
if (args.output) {
std::cout << "output: " << args.output->string() << '\n';
}
return 0;
}

What This Example Shows​

This example converts raw argv text into typed values, rejects invalid ports and profile names during parsing, and checks filesystem-related arguments before the rest of the program runs. On success, the parsed state ends up as optional typed fields for port, profile, and output.

Try It​

The virtual filesystem is configured like this in this environment:

/
└── tmp/ (directory)
cli20@cli20-dev: ~
cli20@cli20-dev:~$ validation

Things to try:

  • Happy path — --port 8080 --profile release_1 --output /tmp/result.txt
  • Port out of range — --port 99999 --profile dev to see range fail
  • Invalid profile — --port 80 --profile My-Profile to see regex reject uppercase
  • Missing required args — just --output /tmp/x to see both required args reported
  • Help — --help