openapi-generator icon indicating copy to clipboard operation
openapi-generator copied to clipboard

[REQ] Pattern validation in Go generator

Open onitake opened this issue 6 years ago • 2 comments

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

The go generator currently doesn't support any form of string validation.

OpenAPI has a pattern parameter on properties that allows specifying a validation regex, and this is supported for some generators, but not Go.

Describe the solution you'd like

There are several Go packages available that support regex validation on struct fields via annotations.

I'm using https://github.com/go-validator/validator/tree/v2 at the moment, with structs of this form:

type MyObject struct {
	// An IPv4 address
	IPAddress string `json:"IPAddress" validate:"regexp=^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$"`
}

This struct should be generated by an OpenAPI definition like this:

MyObject:
  type: object
  properties:
    IPAddress:
      type: string
      description: An IPv4 address
      pattern: '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$'

Describe alternatives you've considered

Since the pattern field doesn't do anything, I'm using x-go-custom-tag instead, but this isn't portable to other languages:

MyObject:
  type: object
  properties:
    IPAddress:
      type: string
      description: An IPv4 address
      x-go-custom-tag: validate:"regexp=^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$"

Additional context

onitake avatar Feb 13 '20 17:02 onitake

Any plans for this? Adding this manually after model generation seems like a hassle and prone to maintainability mistakes.

stijnderyckere avatar Oct 30 '20 17:10 stijnderyckere

Seems that it is not ready yet.

We have got a similar situation: several oneOf choices and they can be distinguished only in runtime by pattern. Need to add custom validation to model_simple.mustache

maxlapshin avatar May 24 '24 12:05 maxlapshin

@stijnderyckere please, take a look at my PR. Maybe it will help.

maxlapshin avatar May 25 '24 12:05 maxlapshin