Skip to content
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

Enhancement request: make it possible to pass params to custom validators #19

Closed
maacl opened this issue Nov 18, 2023 · 4 comments
Closed

Comments

@maacl
Copy link

maacl commented Nov 18, 2023

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.

@yassun7010
Copy link
Owner

@maacl

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)
}

@yassun7010
Copy link
Owner

@maacl

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.

@maacl
Copy link
Author

maacl commented Jan 7, 2024 via email

@yassun7010
Copy link
Owner

@maacl

I released v0.17.0.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants