Keats / validator

Simple validation for Rust structs
MIT License
2.01k stars 144 forks source link

Set regex literal in attribute #149

Open GREsau opened 3 years ago

GREsau commented 3 years ago

Currently, the regex attribute accepts a path to a Regex variable, which would typically be created by something like lazy_static or OnceCell. It would be more convenient for consumers of this library if you could pass in a string literal to be used as a regex, e.g.

#[derive(Validate)]
pub struct Struct {
    #[validate(regex(pattern = r"^[Hh]ello\b"))]
    s: String,
}

I see this approach was considered in #1 but dropped as it was easier to just take a path to an existing variable.

  • use lazy_static inside the generated impl but that requires the end user adding lazy_static manually to their dependencies (afaik)

It could also be achieved by re-exporting lazy_static from the validator crate - potentially with a #[doc(hidden)] as it's just an implementation detail, not public API. In the future hopefully we'll have rust-lang/rust#74465 stable so we can stop using lazy_static entirely

Keats commented 3 years ago

I don't think it makes sense thinking about it again. You won't know the regex path it will be compiled to so if you want to re-use the regex you will need to have it in 2 places instead of one.

GREsau commented 3 years ago

I don't think it's uncommon to only use the regex in one place, so I'd argue the increased simplicity and readability in this case is still worth it. In cases where you do want to reuse the regex, you would still have the option of passing in the path.

rakshith-ravi commented 2 years ago

While this issue is open, I'd like to note that this issue should be kept open, since it can possibly be fixed in a future Rust release. Now that we have panicking available in consts, we can possibly (in the future), have the regex compiled in a const function and only be matched at runtime. All the compilation of the regex will happen at compile time. This is a problem I've personally been trying to solve in my own repo. I'd like to take this up once const fns mature a bit more and once we can do Regex::new inside a const function.