Documentation
¶
Overview ¶
Package apivalidation provides struct validation with automatic OpenAPI 3 schema generation.
Define validation rules by implementing Ruler on your structs:
func (o *Order) Rules() []*FieldRules {
return []*FieldRules{
Field(&o.ID, Required),
Field(&o.Amount, Min(0.01)),
}
}
Then validate with a single call:
err := Validate(&order)
For HTTP handlers, UnmarshalAndValidate and DecodeAndValidate combine JSON decoding with validation in one step.
Sub-packages:
- openapi – OpenAPI schema generation, Swagger UI serving, and endpoint helpers
- transform – struct string transformation utilities
- is – common string format validation rules
Index ¶
- Variables
- func DecodeAndValidate(r io.Reader, dst any) error
- func DecodeAndValidateContext(ctx context.Context, r io.Reader, dst any) error
- func MissingRules(structPtr any, exclude ...string) []string
- func NewSchemaRefForValue(value any) (*openapi3.SchemaRef, error)
- func UnmarshalAndValidate(b []byte, dst any) error
- func UnmarshalAndValidateCtx(ctx context.Context, b []byte, dst any) error
- func Validate(value any) error
- func ValidateCtx(ctx context.Context, value any) error
- func ValidateStruct(structPtr any, fields []*FieldRules) error
- type ContextNormalizer
- type ContextRuler
- type DateRule
- type FieldRules
- type Normalizer
- type Rule
- func By(f RuleFunc, desc string) Rule
- func Custom(f func(any) error, desc string) Rule
- func Default(a any) Rule
- func Deprecate() Rule
- func Describe(desc string) Rule
- func Each(rules ...Rule) Rule
- func Example(ex any) Rule
- func HasAlphabetic() Rule
- func In(values ...any) Rule
- func KeyIn(values ...string) Rule
- func Length(lo, hi int) Rule
- func Max(threshold any) Rule
- func Min(threshold any) Rule
- func NewStringRule(validator func(string) bool, desc string) Rule
- func NewStringRuleDecimalMax(i uint) Rule
- func NewStringRuleWithError(validator func(string) bool, err validation.Error, desc string) Rule
- func NonCreditCardNumber() Rule
- func Skip(desc string) Rule
- func Unique(f func(a int) any, desc string) Rule
- type RuleFunc
- type Ruler
- type ValidationErrors
- type ValueRuler
- type WhenRule
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var Empty = absentRule{validation.Empty, true}
Empty checks if a not nil value is empty.
var Nil = absentRule{validation.Nil, false}
Nil is a validation rule that checks if a value is nil.
var NotNil = notNilRule{Rule: validation.NotNil}
NotNil is a validation rule that checks if a value is not nil.
var Required = requiredRule{ validation.Required, "required", }
Required is a validation rule that checks if a value is not empty.
Functions ¶
func DecodeAndValidate ¶
DecodeAndValidate reads JSON from r into dst using a streaming decoder, then normalizes and validates. Use this instead of UnmarshalAndValidate when reading directly from an io.Reader such as an HTTP request body.
func DecodeAndValidateContext ¶
DecodeAndValidateContext is like DecodeAndValidate but passes a context to ContextNormalizer.Normalize and ContextRuler.Rules.
func MissingRules ¶
MissingRules returns the names of exported struct fields that have no corresponding rule in the Ruler's Rules(). Embedded Ruler fields are expanded and their inner fields checked recursively.
Automatically excluded:
- json:"-"
- docs:"skip"
- validate:"-" (field intentionally has no rules)
Use in tests to catch forgotten fields:
assert.Empty(t, v.MissingRules(&MyStruct{}))
assert.Empty(t, v.MissingRules(&MyStruct{}, "OptionalField"))
func NewSchemaRefForValue ¶ added in v0.0.2
NewSchemaRefForValue generates an OpenAPI schema for the given value, applying validation rules from types that implement Ruler, ContextRuler, or ValueRuler.
func UnmarshalAndValidate ¶
UnmarshalAndValidate decodes JSON from r into dst, then validates. If dst implements Normalizer, recursively normalizes (top level first, then nested structs, slices, maps) before validation.
Example ¶
package main
import (
"fmt"
v "github.com/Gobd/apivalidation"
)
type User struct {
Name string `json:"name"`
Email string `json:"email"`
Age int `json:"age"`
}
func (u *User) Rules() []*v.FieldRules {
return []*v.FieldRules{
v.Field(&u.Name, v.Required, v.Length(1, 100)),
v.Field(&u.Email, v.Required),
v.Field(&u.Age, v.Min(0), v.Max(150)),
}
}
func main() {
body := []byte(`{"name":"Bob","email":"[email protected]","age":25}`)
var user User
if err := v.UnmarshalAndValidate(body, &user); err != nil {
fmt.Println(err)
return
}
fmt.Println(user.Name)
}
Output: Bob
func UnmarshalAndValidateCtx ¶
UnmarshalAndValidateCtx is like UnmarshalAndValidate but passes a context to ContextNormalizer.Normalize and ContextRuler.Rules.
func Validate ¶
Validate is the single entry point for all validation. If value implements Ruler, validates struct fields via Rules(). If value implements ValueRuler, applies its rules to the value directly. Collection elements implementing Ruler are auto-validated.
Example ¶
package main
import (
"fmt"
v "github.com/Gobd/apivalidation"
)
type User struct {
Name string `json:"name"`
Email string `json:"email"`
Age int `json:"age"`
}
func (u *User) Rules() []*v.FieldRules {
return []*v.FieldRules{
v.Field(&u.Name, v.Required, v.Length(1, 100)),
v.Field(&u.Email, v.Required),
v.Field(&u.Age, v.Min(0), v.Max(150)),
}
}
func main() {
user := &User{Name: "Alice", Email: "[email protected]", Age: 30}
if err := v.Validate(user); err != nil {
fmt.Println(err)
return
}
fmt.Println("valid")
}
Output: valid
Example (Error) ¶
package main
import (
"fmt"
v "github.com/Gobd/apivalidation"
)
type User struct {
Name string `json:"name"`
Email string `json:"email"`
Age int `json:"age"`
}
func (u *User) Rules() []*v.FieldRules {
return []*v.FieldRules{
v.Field(&u.Name, v.Required, v.Length(1, 100)),
v.Field(&u.Email, v.Required),
v.Field(&u.Age, v.Min(0), v.Max(150)),
}
}
func main() {
user := &User{Age: -1}
err := v.Validate(user)
fmt.Println(err)
}
Output: age: must be no less than 0; email: cannot be blank; name: cannot be blank.
func ValidateCtx ¶
ValidateCtx is like Validate but passes a context to ContextRuler.Rules().
func ValidateStruct ¶
func ValidateStruct(structPtr any, fields []*FieldRules) error
ValidateStruct validates a struct with explicit field rules. Prefer Validate for types implementing Ruler.
Types ¶
type ContextNormalizer ¶
ContextNormalizer is like Normalizer but receives a context. Called by UnmarshalAndValidateCtx before validation.
type ContextRuler ¶
type ContextRuler interface {
Rules(context.Context) []*FieldRules
}
ContextRuler is like Ruler but receives a context (for conditional rules).
type DateRule ¶ added in v0.0.2
type DateRule struct {
validation.DateRule
// contains filtered or unexported fields
}
DateRule validates that a string value matches the given date layout format. Use Date to create one, then chain DateRule.Min and DateRule.Max to constrain the date range for documentation.
func Date ¶
Date creates a date validation rule with the given layout format. Use .Min() and .Max() to constrain the date range for documentation.
Example ¶
package main
import (
"fmt"
"time"
v "github.com/Gobd/apivalidation"
)
type Event struct {
StartDate string `json:"start_date"`
}
func (e *Event) Rules() []*v.FieldRules {
return []*v.FieldRules{
v.Field(&e.StartDate, v.Required, v.Date("2006-01-02").
Min(time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)).
Max(time.Date(2030, 12, 31, 0, 0, 0, 0, time.UTC))),
}
}
func main() {
e := &Event{StartDate: "2025-06-15"}
if err := v.Validate(e); err != nil {
fmt.Println(err)
return
}
fmt.Println("valid")
}
Output: valid
func (*DateRule) Describe ¶ added in v0.0.2
Describe implements Rule by setting the format and date range on the schema.
type FieldRules ¶
type FieldRules struct {
// contains filtered or unexported fields
}
FieldRules binds a struct field pointer to its validation rules.
func Field ¶
func Field[T any](fieldPtr *T, rules ...Rule) *FieldRules
Field creates a FieldRules binding a struct field pointer to its validation rules.
type Normalizer ¶
type Normalizer interface {
Normalize()
}
Normalizer is implemented by types that need custom normalization after unmarshaling. Called by UnmarshalAndValidate before validation. When the top-level type implements Normalizer, normalization recurses into struct fields, slices, maps, and embedded structs, calling Normalize on any nested type that also implements it. Top level is always called first, then children depth-first.
type Rule ¶
type Rule interface {
Validate(value any) error
Describe(name string, schema *openapi3.Schema, ref *openapi3.SchemaRef) error
}
Rule is the interface that all validation rules must implement.
func Custom ¶
Custom returns a validation rule that uses f for validation and desc for documentation.
func Deprecate ¶
func Deprecate() Rule
Deprecate returns a documentation-only rule that marks the field as deprecated in the schema.
func Describe ¶
Describe returns a documentation-only rule that appends desc to the schema description.
func Each ¶
Each returns a validation rule that applies the given rules to each element of a slice or array.
func HasAlphabetic ¶
func HasAlphabetic() Rule
HasAlphabetic returns a validation rule that checks if a string contains at least one alphabetic character.
func Length ¶
Length returns a validation rule that checks if a string's rune length is within the specified range.
func Max ¶
Max returns a validation rule that checks if a value is less than or equal to the specified maximum.
func Min ¶
Min returns a validation rule that checks if a value is greater than or equal to the specified minimum.
func NewStringRule ¶
NewStringRule returns a string validation rule using desc as both the error message and schema description.
func NewStringRuleDecimalMax ¶
NewStringRuleDecimalMax returns a validation rule that limits the number of decimal places in a numeric string.
func NewStringRuleWithError ¶
NewStringRuleWithError returns a string validation rule with a custom error and schema description.
func NonCreditCardNumber ¶
func NonCreditCardNumber() Rule
NonCreditCardNumber returns a validation rule that rejects strings that look like credit card numbers.
type Ruler ¶
type Ruler interface {
Rules() []*FieldRules
}
Ruler is implemented by types that define validation rules for their fields. Use a pointer receiver so field pointers are stable:
func (s *MyStruct) Rules() []*FieldRules {
return []*FieldRules{Field(&s.Name, Required)}
}
type ValidationErrors ¶
type ValidationErrors = validation.Errors
ValidationErrors is a map of field names to their validation errors. It is an alias for validation.Errors from ozzo-validation and implements the error interface with a JSON-friendly string representation.
type ValueRuler ¶
type ValueRuler interface {
ValueRules() []Rule
}
ValueRuler is implemented by non-struct types (e.g. type PaymentMethod string) that carry their own validation rules. The returned rules are automatically applied during both validation and OpenAPI schema generation wherever the type appears as a struct field.
type PaymentMethod string
const (
PaymentACH PaymentMethod = "ach"
PaymentCC PaymentMethod = "cc"
)
func (p PaymentMethod) ValueRules() []Rule {
return []Rule{In(PaymentACH, PaymentCC)}
}
type WhenRule ¶ added in v0.0.2
type WhenRule struct {
validation.WhenRule
// contains filtered or unexported fields
}
WhenRule validates conditionally: it applies one set of rules when the condition is true, and an optional alternative set (via WhenRule.Else) when false. Use When to create one.
func When ¶
When returns a conditional validation rule that applies rules only when condition is true.
Example ¶
package main
import (
"encoding/json"
"fmt"
v "github.com/Gobd/apivalidation"
)
type Payment struct {
Amount float64 `json:"amount"`
Currency string `json:"currency"`
IsDraft bool `json:"-"`
}
func (p *Payment) Rules() []*v.FieldRules {
return []*v.FieldRules{
v.Field(&p.Amount, v.When(!p.IsDraft, "not draft", v.Required, v.Min(0.01)).
Else(v.Min(0.0))),
v.Field(&p.Currency, v.Required, v.In("USD", "EUR", "GBP")),
}
}
func main() {
p := &Payment{Amount: 10.00, Currency: "USD"}
if err := v.Validate(p); err != nil {
fmt.Println(err)
return
}
b, _ := json.Marshal(p)
fmt.Println(string(b))
}
Output: {"amount":10,"currency":"USD"}
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Command example demonstrates apivalidation with an HTTP server serving a Swagger UI and a validated JSON endpoint.
|
Command example demonstrates apivalidation with an HTTP server serving a Swagger UI and a validated JSON endpoint. |
|
Package is provides a list of commonly used string validation rules.
|
Package is provides a list of commonly used string validation rules. |
|
Package openapi generates OpenAPI 3 specifications from struct types that implement [apivalidation.Ruler].
|
Package openapi generates OpenAPI 3 specifications from struct types that implement [apivalidation.Ruler]. |
|
Package transform provides struct transformation utilities for mutating string fields recursively within structs.
|
Package transform provides struct transformation utilities for mutating string fields recursively within structs. |