-
-
Notifications
You must be signed in to change notification settings - Fork 1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Validate argument with regex #1968
Comments
My first thought was: "This is pretty trivial with normal validators!". And indeed: lazy_static! {
static ref RE: Regex = Regex::new("\\d+").unwrap();
}
app.validator(|val| {
if RE.is_match(val)) {
Ok(())
} else {
Err(format!("value '{}' doesn't match the `\\d+` regex", val))
}
}) But on the other side, validators cannot be deserialized from YAML, and "matches a regex" does sound common enough to warrant a special case. I say we might gate it behind Unresolved questions: what about error messages? I have doubts that "value doesn't match regex" is good user-facing message. Perhaps the API should look like: fn regex_validator("-?\\d+", "expected an integer");
// rendered as
"Invalid value `foo`: expected an integer" @pksunkara @kbknapp Any thoughts? |
Agreed on your point about needing a more helpful error, @CreepySkeleton . I personally like the example function you provided where the user supplies an error string. |
How would the error message be written in a YAML file? |
Just as any other tuple would regex_validator:
- r"[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)"
- error message
# or if regex and error are short enough
regex_validator: ["-?\\d+", "expected an integer"]
|
Hi, |
FYI I am considering removing |
Describe your use case
It would be nice to have a clap feature for argument validation via a regex. This would be handy and flexible for users, allowing them custom validations without writing a custom validator to do so, and hopefully without requiring too large of overhead for implementation and testing in clap itself.
Describe the solution you'd like
For example, using clap yaml format, if we want an argument whose value wants only digit values 1 through 100:
This could expand to complex regex use cases, like matching if an arg value is a URL:
Thanks for this very nice arg parsing library!
The text was updated successfully, but these errors were encountered: