Search code examples
rustrust-rocket

Why Rocket validations are not executing on Json?


I have the following code where I use the Rocket validations:

#[derive(Debug, Deserialize, FromForm)]
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

I also tried to add the built-in validation:

#[derive(Debug, Deserialize, FromForm)]
pub struct CreateUserDto<'r> {
    #[field(validate = range(2..10))]
    id: usize,
    #[field(validate = email_validation())]
    pub email: &'r str,
    pub password: &'r str,
}

And here is the endpoint:

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

In both cases the validation didn't work.

Update 1:

It seems like the validations are workign when Form is applied:

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

Any idea how to run it on Json as well?


Solution

  • Rocket implements validation only for forms. As far as I can tell there is no way to trigger validation for other types.

    However, you can use a different validation crate. validator seems to be the most popular option, and there is rocket-validation that provides a rocket guard for validator.