how to validate a cli argument in clap 4.0.9

710 views Asked by At

I'm currently restricted to clap 4.0.9 and I have the following code:

#[derive(Debug, clap::Parser)]
pub struct RunCmd {
    #[clap(long, default_value_t = 7000)]
    pub port: u16,
}

I want to create a function that validates the port that is passed like this:

fn validate_port(p: &str) -> Result<u16, String> {
    let port = p.parse::<u16>().map_err(|_| "Invalid port number")?;
    if port >= 1024 {
        Ok(port)
    } else {
        Err("Port number must be between 1024 and 65535".to_owned())
    }
}

is there a way to call validate_port to validate the port?

2

There are 2 answers

0
ezio On

Thanks to the comment of @isaactfa this is how it worked:

#[clap(long, default_value_t = 7000, value_parse = validate_port)]
0
lowit On

For those who came here from the Internet just like me.
In this version (4.0.9), but also in the latest ones, you can use the value_parser! macro

For new versions of clap with syntax based on derive Parser

#[derive(Parser)]
#[command(author, version, about)]
struct Cli {
    #[arg(long, value_parser=clap::value_parser!(u16).range(1024..),)]
    port: u16,
}

Example for 4.0.9 version (and no-derive syntax)

let mut cmd = clap::Command::new("example")
    .arg(
        clap::Arg::new("port")
            .value_parser(clap::value_parser!(u16).range(1024..)
        )
    );

https://docs.rs/clap/4.0.9/clap/macro.value_parser.html