Skip to content

[REQ][Go] Validate enums #7294

Description

@onitake

Is your feature request related to a problem? Please describe.

The Go models generated by openapi-generator currently don't contain any kind of input validation code.

Using the x-go-custom-tag: validate:"regexp=..." syntax, it is possible to at least add some validation tags for external validation modules (this example is intended for gopkg.in/validator.v2).

This will not work when referencing enums - in this case, the go generator will create a separate model source, and anything that should be attached to the containing struct (such as tags) will get dropped.

Describe the solution you'd like

The Go generator should at least generate some validation functions on the enum type that can be called after deserialization.

Or even better, it should generate an UnmarshalJSON function that validates, so it will be called automatically by the JSON decoder.

Describe alternatives you've considered

The only alternative I can use at the moment is using inline enums - in that case, x-go-custom-tag will work as expected.

Additional context

Reference example

components:
  schemas:
    Status:
      type: string
      enum:
      - ok
      - error
      x-go-custom-tag: validate:"regexp=^ok|error$"
    Test:
      type: object
      properties:
        Status:
          $ref: '#/components/schemas/Status'

generates

type Status string
const (
	STATUS_OK Status = "ok"
	STATUS_ERROR Status = "error"
)
// no validation code for Status
type Test struct {
        // x-go-custom-tag is ignored
	Status Status `json:"Status"`
}

Inline example

components:
  schemas:
    Status:
    Test:
      type: object
      properties:
        Status:
          type: string
          enum:
          - ok
          - error
          x-go-custom-tag: validate:"regexp=^ok|error$"

generates

// no enum type
type Test struct {
        // x-go-custom-tag is added
	Status string `json:"Status" validate:"regexp=^ok|error$"`
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions