Skip to main content

Validation constraints

apiary maps the common go-playground/validator rules you already write onto JSON-Schema constraints, with no extra annotations.

validate: ruleJSON Schema (by field type)
requiredadds the field to required
min=N / max=Nminimum/maximum (number), minLength/maxLength (string), minItems/maxItems (array)
gt/gte/lt/lte=NexclusiveMinimum/minimum/exclusiveMaximum/maximum (numbers)
len=Nexact length / item count
oneof=a b cenum: [a, b, c]
emailformat: email
uuidformat: uuid
url / uriformat: uri
ipv4 / ipv6format: ipv4 / ipv6
hostnameformat: hostname

Unknown rules are ignored. Constraints apply to request-body fields and to path/query/header parameters.

type CreateUserRequest struct {
Username string `json:"username" validate:"required,min=3,max=32"`
Email string `json:"email" validate:"required,email"`
Role string `json:"role" validate:"oneof=admin user guest"`
Age *int `json:"age,omitempty" validate:"gte=13,lte=120"` // nullable + bounded
}

generates:

username: { type: string, minLength: 3, maxLength: 32 }
email: { type: string, format: email }
role: { type: string, enum: [admin, user, guest] }
age: { type: [integer, "null"], minimum: 13, maximum: 120 }
required: [username, email]

Go type to JSON Schema mapping

Go typeJSON Schema
string / bool{type: string} / {type: boolean}
int, int32 / int64{type: integer, format: int32 / int64}
float32 / float64{type: number, format: float / double}
time.Time{type: string, format: date-time}
uuid.UUID{type: string, format: uuid}
[]T / map[K]Varray / object
Struct$ref to a component
*T (scalar)nullable (type: [T, "null"])
*Structnullable (anyOf: [{$ref}, {type: "null"}])

example: and default: tag values are coerced to the field's JSON type, so example:"42" on an integer field renders as example: 42, not "42".