rwf2 / Rocket

A web framework for Rust.

Home Page:https://rocket.rs

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Validation not invoked on Json

vlio20 opened this issue · comments

Rocket Version

0.5.0

Operating System

macos

Rust Toolchain Version

rustc 1.76.0 (07dca489a 2024-02-04)

What happened?

Custom validation is never invoked.

Test Case

I have the following code:

#[derive(Debug, Deserialize, FromForm)]
#[serde(crate = "rocket::serde")]
pub struct CreateUserDto<'r> {
    #[field(validate = email_validation())]
    email: &'r str,
    password: &'r str,
}

fn email_validation(email: &str) -> Result<()> {
    let re: Regex = Regex::new(r"^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$").unwrap();

    if !re.is_match(email) {
        Err(Error::validation("invalid email address"))?;
    }

    Ok(())
}

In that code I am trying to validate the email field according to a given regex. For some reason the email_validation function is never called.

Any idea why? I was following the Rocket documentation as seen here: https://api.rocket.rs/master/rocket/form/validate/#custom-validation



### Log Output

```shell
No errors when running the above code. The validation is never executed - validated with wrong input and with with a debugger breakpoint.

Additional Context

No response

System Checks

  • My bug report relates to functionality.
  • I have tested against the latest Rocket release or a recent git commit.
  • I have tested against the latest stable rustc toolchain.
  • I was unable to find this issue previously reported.

Invoked at what point? Your code doesn't include any routes.

@SergioBenitez, this is the route:

#[post("/", data = "<input>")]
fn creart_user(input: Json<CreateUserDto>) {
    let user = input.into_inner();
    println!("email {0}, password: {1}", user.email, user.password);
}

It seems like the validations are not running on Json. They do run on Form.

Maybe it is related to the following:
#2110

There's likely no bug here. You're using the Json type which works through the Deserialize trait. On the other hand, the field attribute you're using to validate is part of the FromForm trait and is not involved during deserialization.

Is there any way to make the Json type to preform the Field validations?

Not at the moment. They simply work through different mechanisms. I do have a plan to align the different "data" processors to make that happen, but that will be a larger effort.