Keats/validator

Support enum

Opened this issue · 4 comments

Hi,

I would like to validate enums, for example

enum A {
    A1 { a: u32 },
    A2 { b: String },
}

Is this possible?

Keats commented

Not currently, this seems like a significant amount of work and I won't have the time/will to do it myself. If someone manages to add it though, it seems like a good feature.
You can do the following in the meantime

enum A {
  A1(A1),
  A2(A2),
}

and put the validation on the structs.

Just a note for people finding this.

While enums aren't supported for proc macros at the moment, if the issue you are trying to solve is just allowing traversal of enums with the nesting #[validate] feature you can implement this manually like so:

#[derive(Debug, Serialize, Deserialize)]
pub enum TargetType {
    CircleTarget(CircleTarget),
    PolygonTarget(PolygonTarget),
    AlertTarget(AlertTarget),
}
impl Validate for TargetType {
    #[allow(unused_mut)]
    fn validate(&self) -> ::std::result::Result<(), ::validator::ValidationErrors> {
        let mut errors = ::validator::ValidationErrors::new();
        let mut result = if errors.is_empty() {
            ::std::result::Result::Ok(())
        } else {
            ::std::result::Result::Err(errors)
        };
        match self {
            TargetType::CircleTarget(t) => {
                ::validator::ValidationErrors::merge(result, "CircleTarget", t.validate())
            }
            TargetType::PolygonTarget(t) => {
                ::validator::ValidationErrors::merge(result, "PolygonTarget", t.validate())
            }
            _ => result,
        }
    }
}

Then you put the Validate derive on the struct on either side of the enum, and off you go!

I'm having the issue that it does not validate the field that is an enum with #[validate] on it. If I call the validate() on the field (the enum) it works. Any suggestions?

The proc macro has been rewritten, it should be easier to add support for enums if someone wants to.