Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support enum #77

Open
jannschu opened this issue Aug 7, 2019 · 4 comments
Open

Support enum #77

jannschu opened this issue Aug 7, 2019 · 4 comments

Comments

@jannschu
Copy link

jannschu commented Aug 7, 2019

Hi,

I would like to validate enums, for example

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

Is this possible?

@Keats
Copy link
Owner

Keats commented Aug 8, 2019

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.

@jamessewell
Copy link

jamessewell commented Sep 25, 2019

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!

@johansmitsnl
Copy link

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?

@Keats
Copy link
Owner

Keats commented Mar 30, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants