yassun7010 / serde_valid

JSON Schema based validation tool using serde.
MIT License
46 stars 10 forks source link

Validations not working for nested structs/enums #18

Closed RamDurgaSai closed 11 months ago

RamDurgaSai commented 11 months ago

Validations for nested structs

  use serde::{Deserialize, Serialize};
  use serde_valid::Validate;
  extern crate serde_valid;

  #[derive(Deserialize, Serialize, Validate, Debug)]
  pub struct Apple{
      #[validate(minimum=1, message="Weight should be greater then 5")]
      weight: usize,

      color: String
  }

  #[derive(Deserialize, Serialize, Validate, Debug)]
  pub struct Fruit{
      apple: Apple
  }

  fn main() {
      let apple = Apple {weight: 0, // Invalid Weight
          color: "Red".into()};

      println!("Valid Apple:- {}", apple.validate().is_ok()); // Validations for Apple works

      let fruit = Fruit{apple};

      println!("Valid Fruit:- {}", fruit.validate().is_ok()); // Not for Fruit

  }

In the example you provided, the "Apple" struct has an invalid weight, and the validations are working for apples. However, when you apply the same validations to "Fruit" the validations are not functioning as expected.

RamDurgaSai commented 11 months ago

Found solution

Need to add #[validate] to the field to validate

[derive(Deserialize, Serialize, Validate, Debug)]

pub struct Fruit{

[validate] // <-- here

apple: Apple }