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

Field value is passed to a custom function by value instead of by reference, contradicting with README.md. #331

Open
your-diary opened this issue Jun 25, 2024 · 1 comment

Comments

@your-diary
Copy link

According to README.md (emphasis mine):

custom

Calls one of your functions to perform a custom validation. The field reference will be given as a parameter to the function, which should return a Result<(), ValidationError>.

However, as far as I tested:

  • For String field, a custom function receives &String, which is as expected.

  • However, for usize field, a custom function receives usize instead of &usize, contradicting with the snippet above.

Minimal Working Example

use validator::{Validate, ValidationError};

//compile error (changing `&usize` to `usize` fixes the error)
fn validate_usize(_: &usize) -> Result<(), ValidationError> {
    Ok(())
}

//OK (inconsistent with the function above)
fn validate_string(_: &str) -> Result<(), ValidationError> {
    Ok(())
}

#[derive(Debug, Validate)]
struct S {
    #[validate(custom(function = "validate_usize"))]
    i: usize,
    #[validate(custom(function = "validate_string"))]
    j: String,
}

fn main() {
    let s = S {
        i: 10,
        j: "hello".to_string(),
    };
    assert!(s.validate().is_ok());
}
   Compiling a v0.1.0 (/Users/user/a)
error[E0308]: mismatched types
  --> src/main.rs:13:17
   |
13 | #[derive(Debug, Validate)]
   |                 ^^^^^^^^ expected `&usize`, found `usize`
14 | struct S {
15 |     #[validate(custom(function = "validate_usize"))]
   |                                  ---------------- arguments to this function are incorrect
   |
note: function defined here
  --> src/main.rs:4:4
   |
4  | fn validate_usize(_: &usize) -> Result<(), ValidationError> {
   |    ^^^^^^^^^^^^^^ ---------
   = note: this error originates in the derive macro `Validate` (in Nightly builds, run with -Z macro-backtrace for more info)

For more information about this error, try `rustc --explain E0308`.
error: could not compile `a` (bin "a") due to 1 previous error
@Keats
Copy link
Owner

Keats commented Jun 25, 2024

The docs should be updated: fields that can be copied cheaply (essentially all numbers) are passed by values, the rest by reference.

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