Skip to content

Validation tags#237

Closed
dududko wants to merge 3 commits into
oapi-codegen:masterfrom
dududko:validation-tags
Closed

Validation tags#237
dududko wants to merge 3 commits into
oapi-codegen:masterfrom
dududko:validation-tags

Conversation

@dududko
Copy link
Copy Markdown
Contributor

@dududko dududko commented Oct 12, 2020

New Feature: validation tags

This PR adds generation of validation tags, which can be used by validator - a framework for validation. This approach is recommended by echo web framework.

It is the alternative solution to request validation by github.com/getkin/kin-openapi, which uses the source openapi spec to create Swagger container and use it to validate incoming requests.

Example

# input spec
components:
  schemas:
    StructA:
      required:
        - requiredString
        - color
        - rangeInt
      properties:
        requiredString:
          type: string
        rangeInt:
          type: integer
          format: int64
          minimum: 2
          maximum: 42
        color:
          type: string
          enum:
            - black
            - white
// StructA defines model for StructA.
type StructA struct {
	RangeInt       int64  `json:"rangeInt,omitempty" validate:"required,gte=2,lte=42"`
	RequiredString string `json:"requiredString" validate:"required"`
	Color          Color  `json:"color" validate:"required,oneof=black white"`
}
a := types.StructA{
	RangeInt: 99,
	Color: "orange",
}

// stdout: map[StructA.Color:Color must be one of [black white] StructA.RangeInt:RangeInt must be 42 or less StructA.RequiredString:RequiredString is a required field]
fmt.Println(validate.Struct(a).(validator.ValidationErrors).Translate(translator))

you can find more examples in this file internal/test/validator/validator_test.go

Credits: @madesst, @dududko

@dududko
Copy link
Copy Markdown
Contributor Author

dududko commented Oct 12, 2020

There is a related PR which uses different validation framework - ozzo-validation #225.

@chemidy
Copy link
Copy Markdown

chemidy commented Feb 5, 2021

Maybe you can add an option validator to -generate like chi-server, so we can have another kind of validator like ozzo-validation !

@dududko
Copy link
Copy Markdown
Contributor Author

dududko commented Mar 18, 2021

FYI: I decided to change this solution in favor of vanilla approach for request/response validation.
Was not able to use it because the external references were not fully supported in the embedded spec.
I fixed this in #320

@dududko
Copy link
Copy Markdown
Contributor Author

dududko commented Apr 4, 2021

Closed in favor of #327

@dududko dududko closed this Apr 4, 2021
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