Skip to content

Conversation

@mbyio
Copy link

@mbyio mbyio commented Dec 2, 2023

Changes

  • Add a new validate flag
  • When the validate flag is true, generate a Validate() error method that verifies the enum is set to a proper value
  • Some small quality of life improvements to the golden test runner
  • Run gofmt on some of the files (this just happened automatically because of my editor)

Why

We currently have a IsA<Type>() bool method, but the name is different for every enum type. That basically makes it impossible to integrate it with Go interfaces or generics.

I return an error instead of a bool, because returning an error lets us provide more information on why the value is invalid. And again, it would also compose better with any generic validation code (you could, for example, recursively validate fields in a struct, and combine all the errors using errors.Join).

Note

I didn't see any more well known method signatures than Validate() error, but if there are any, we could switch and use that instead.

@peczenyj
Copy link

Hey, this is a wonderful idea. for instance, when using github.com/go-playground/validator/v10 I have only two options:

  1. duplicate all possible string values in oneof tag - and I need to keep track all changes if I include a new value.
  2. create a custom validator ( is-foo ) and I need to manually tag validate:is-foo AND include the custom validator else where.

the second option is not a big problem, but the code is ^C ^V in the end

by adding a Validate() error in the code generate solve 60% of my problems

do you need some help to merge this feature? may I help to test?

Regards

@peczenyj
Copy link

ps: perhaps should be interesting have a way to customize the method validation name. and Validate can be a default value

@mbyio
Copy link
Author

mbyio commented Jan 3, 2025

Thanks @peczenyj. Since it has been over a year, I don't think I will work on this anymore, but please be my guest! I still think it is a useful feature!

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

Successfully merging this pull request may close these issues.

2 participants