[Ask] Did validator can't be used with `serde_json::from_str` ?
Closed this issue · 2 comments
weiztech commented
I'm trying to use validator
but it seems it does not trigger the validation and always returns success result.
depedencies
[dependencies.validator]
version = "0.16.1"
features = ["derive"]
Code
#[derive(Validate, Debug, Serialize, Deserialize)]
struct User {
id: u64,
#[validate(length(max = 1))]
username: String,
address: String,
}
let data = r#"
{
"id": 43,
"username": "Joel",
"address": "+123 55555"
}"#;
let data = serde_json::from_str::<User>(data);
match data {
Ok(person) => {
println!("Deserialized person: {:?}", person);
}
Err(error) => {
println!("Failed to deserialize data. Error: {}", error);
}
}
is it possible to trigger the validation when using serde_json::from_str
?
pintariching commented
I think you need to call validate()
on the deserialized User
struct in the match statement. Or if you want a one-liner try
let validation_result = serde_json::from_str::<User>(data).is_ok_and(|user| user.validate());
Not entirely sure if this will work.
weiztech commented
since it's not possible to validate directly using serde_json::from_str
, I also think should use validate
method for now. Thanks