Skip to content

feat: add Valid() method to generated enum types#2227

Merged
mromaszewicz merged 2 commits intooapi-codegen:mainfrom
mromaszewicz:feat/enum-validation
Feb 17, 2026
Merged

feat: add Valid() method to generated enum types#2227
mromaszewicz merged 2 commits intooapi-codegen:mainfrom
mromaszewicz:feat/enum-validation

Conversation

@mromaszewicz
Copy link
Member

Generate a Valid() bool method on each enum type that returns true when the receiver matches one of the defined enum constants and false otherwise. This lets callers validate enum values at runtime with a simple method call instead of hand-writing switch statements.

This is default-on because it only adds a new method to an already generated type -- existing code that does not call Valid() is completely unaffected, so this should be very unlikely to break anything.

Generate a Valid() bool method on each enum type that returns true when
the receiver matches one of the defined enum constants and false
otherwise. This lets callers validate enum values at runtime with a
simple method call instead of hand-writing switch statements.

This is default-on because it only adds a new method to an already
generated type -- existing code that does not call Valid() is completely
unaffected, so this should be very unlikely to break anything.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Copy link
Member

@jamietanna jamietanna left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice!

Copy link
Member

@jamietanna jamietanna left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From #2181 I do wonder if it'd be useful to be able to get the list of valid enum names, though, i.e. as a slice

But maybe we can see if this solves the underlying need folks have

It turns out we don't need a sorted map of names, since we have
the same thing already present on the template context in a
different way.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@mromaszewicz
Copy link
Member Author

From #2181 I do wonder if it'd be useful to be able to get the list of valid enum names, though, i.e. as a slice

But maybe we can see if this solves the underlying need folks have

I think it does, because you can always validate in your own code with something like MyEnum(x).Valid(). We can certainly return all the enum values in the future if needed, or even make a Stringer out of it.

@mromaszewicz mromaszewicz merged commit 4b72bdb into oapi-codegen:main Feb 17, 2026
26 checks passed
@jamietanna jamietanna added the enhancement New feature or request label Feb 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants