Keats / validator

Simple validation for Rust structs
MIT License
1.97k stars 141 forks source link

Add static parameters to custom validator functions? #247

Open timvisee opened 1 year ago

timvisee commented 1 year ago

I'm looking for a way to add additional parameters to custom validator functions. For example:

struct ExampleStruct {
    #[validate(custom(function = "custom_range", params = "(1, 128)"))]
    name: String,
    #[validate(custom(function = "custom_range", params = "(4, 32)"))]
    alias: String,
}

fn custom_range(value: &String, params: (u64, u64)) -> Result<(), ValidationError> {
    // Some logic here...
}

This would be much better than having a separate function for each configuration such as custom_range_1_128 and custom_range_4_32.

This is different than the arg = "(i32, i32)" feature, because arg is to attach references to external data during validation with validate_args(...). Instead I'd like to specify static parameters inside the struct definitions itself.

Is something like this currently possible? If not, can I submit a PR to implement this?

Note: I understand that in this example the built-in range validator would suffice. I'm just using range as easy to understand example rather than the more complex case I'm currently dealing with.

Keats commented 1 year ago

Why limit it to static? I can bet 2 seconds after this is released someone will want references

timvisee commented 1 year ago

The point is to provide additional parameters to custom validators. Using arg with external references is not an option in our case, partially because we use deeply nested structs.

I meant static as in hardcoded within the validate attribute definition. Yes, that is something we're looking for in our case. That is to prevent boilerplate like this:

https://github.com/qdrant/qdrant/blob/79ba0c95db5d60bf20c8583b4d0651b1bf8e7e76/lib/api/src/grpc/validate.rs#L90-L156