Enhancement request: make it possible to pass params to custom validators
Closed this issue · 4 comments
It would be very useful if you could do:
#[validate(custom(user_validation = 24))]
Even better if you could pass a struct or vector with multiple values.
Sorry, I am late to see this.
custom is basically a representation of the method name only.
I once tried a another idea, which I ended up not adopting.
Couldn't we use other fields for validation of some field?
(In fact, an early implementation did just that)
struct A {
#[validate(custom(my_validation(val1, val2)))]
val1: i32,
val2: i32,
}
Consider this in the Unnamed Struct.
struct A {
#[validate(custom(my_validation(0, 1)))]
i32,
i32,
}
I'm stumped!!
We can't determine if the integer is a field number in an unnamed structure or a value to a function argument.
For example, the following additions conflict with multiple field validation
fn my_validation(val1: i32, param1: i32, param2: i32) {
...
}
struct A {
#[validate(custom(my_validation(1, 2)))]
i32
}
Considering the use of web applications,
The above ideas are practical, but cannot be co-located with those idea.
To prevent such complexity from occurring, the design intentionally limits features.
custom
: Validation of a single field
rule
: Validation of multiple fields
Currently, functions must be created and used on a case-by-case basis.
fn my_validation_0(val1: i32) {
my_validation(val1, 0)
}
Today I upgraded to syn v2, and are now able to write by closure as follows.
use serde_valid::Validate;
fn user_validation(_val: &i32, param1: bool) -> Result<(), serde_valid::validation::Error> {
Ok(())
}
#[derive(Validate)]
struct SampleStruct {
#[validate(custom(|v| user_validation(v, true)))]
val: i32,
}
let s = SampleStruct { val: 1 };
assert!(s.validate().is_ok());
It should be available in the next release.