Keats / validator

Simple validation for Rust structs
MIT License
2.07k stars 151 forks source link

How can I use a validator on an enum #341

Closed dev-davexoyinbo closed 4 months ago

dev-davexoyinbo commented 4 months ago

How can I use a validator on an enum eg

#[derive(Validate, Serialize, Deserialize)]
enum SomeEnum {
   TypeOne {
      title: String,
      count: u64,
   },
   TypeTwo {
      title: String,
      descriiption: String
   }
}
dev-davexoyinbo commented 4 months ago

Gotten a solution. I just implement a validate method on the enum and forward it

#[derive(Validate)]
struct TypeOne {
      title: String,
      count: u64,
   }

  #[derive(Validate)]
  struct TypeTwo {
      title: String,
      descriiption: String
   }

   enum SomeEnum {
      TypeOne(TypeOne),
      TypeTwo(TypeTwo)
   }

   impl SomeEnum {
      fn validate(&self) -> Result<(), ValidationErrors> {
         let v: Box<dyn Validate> = match self {
             Self::TypeOne(v) => Box::new(v),
             Self::TypeTwo(v) => Box::new(v)
         };

         v.validate()
      }
   }

I can now run the validate on an instance of the enum

let type_one_enum = SomeEnum::TypeOne(TypeOne {
   title: "title".tp_string(),
   count: 7,
});

type_one_enum.validate()?;
Keats commented 4 months ago

That should be possible to add natively