somehowchris / rocket-validation

A guard to validate data received by rocket via validator
16 stars 4 forks source link

how to use custom validation #19

Closed allanHaroldMarques closed 1 year ago

allanHaroldMarques commented 1 year ago

Hello,

Im try to use custom validation or regex validation. But i could used:

use serde::{Serialize, Deserialize};
use rocket_validation::{Validate, ValidationErrors};

#[derive(Debug, Serialize, Deserialize, Validate)]
#[serde(crate = "rocket::serde")]
pub struct CatOnwerCreate {
    #[validate(custom(function = "validate_something"))]
    pub cat_gender: String,
}

fn validate_something(cat_gender: &String) -> Result<(), ValidationErrors> {
    return Ok(());
}

appear this error: unresolved import validatorrustc[Click for full compiler diagnostic](rust-analyzer-diagnostics- cat_owner_create.rs(5, 41): a similar path exists: rocket_validation::validator

can help?

allanHaroldMarques commented 1 year ago

I managed to do it with regex like this:

use serde::{Serialize, Deserialize};
use regex::Regex;
use rocket_validation::{Validate};

use lazy_static::lazy_static;

#[derive(Debug, Serialize, Deserialize, Validate)]
#[serde(crate = "rocket::serde")]
pub struct CatOnwerCreate {
    #[validate(regex(path = "RE_TWO_CHARS"))]
    cat_gender: String,
}

lazy_static! {
    static ref RE_TWO_CHARS: Regex = Regex::new("/^(apple|banana)$/").unwrap();
}

But, when i put in the route:


#[post("/cat-owner", format = "application/json", data = "<cat_onwer>")]
pub fn create_cat_owner(cat_onwer: Validated<Json<CatOnwerCreate>>) -> Json<CatOnwerCreate> {
    cat_onwer.into_inner()
}

i get this error:

the trait bound Validated<rocket::serde::json::Json<CatOnwerCreate>>: FromData<'_> is not satisfied the following other types implement trait FromData<'r>:

somehowchris commented 1 year ago

May I ask which rocket version you are using? Or in general a snippet of the Cargo.toml with the crates in use

allanHaroldMarques commented 1 year ago

I managed to solve. It was the version. Thank you. But now, i have another problem. I gonna open another issue, because it's other subject;