Skip to content

Validation ​

Added: v1.0.0

Zen provides a pluggable Validator interface with a built-in default backed by go-playground/validator and familiar tag-based rules.

Validator Interface ​

go
type Validator interface {
    Validate(i any) error
}

Implement this to plug in any validation library. The default uses go-playground/validator/v10 with validate struct tags.

Manual Validation ​

A default validator (backed by go-playground/validator) is installed at startup, but binding never validates on its own. After binding, call c.Validate() explicitly:

go
type SignupRequest struct {
    Email    string `json:"email" validate:"required,email"`
    Password string `json:"password" validate:"required,min=8"`
    Age      int    `json:"age" validate:"gte=18"`
}

r.POST("/signup", func(c *zen.Ctx) {
    var req SignupRequest
    if err := c.BindJSON(&req); err != nil {
        c.Error(400, err.Error())
        return
    }
    if err := c.Validate(&req); err != nil {
        c.Error(400, err.Error())
        return
    }
    // req is valid - proceed
})

Validate is available both on *Ctx (c.Validate(&req)) and on *Engine (r.Validate(&req) for use outside request handlers). It returns nil if no validator is set.

Auto-Validation ​

Call EnableAutoValidation() on the engine once at startup to have all bind methods run validation automatically after decoding - Bind, BindJSON, BindXML, BindForm, BindBody, BindHeaders, BindPathValues, and BindQueryParams:

go
r := zen.New(":8080")
r.EnableAutoValidation()

r.POST("/signup", func(c *zen.Ctx) {
    var req SignupRequest
    if err := c.BindJSON(&req); err != nil {
        c.Error(400, err.Error())
        return
    }
    // req is already validated - proceed
})

Custom Validation Tags ​

Register custom validation rules on the engine's underlying go-playground/validator instance:

go
r.DefaultValidator().RegisterValidation("is-even", func(fl validator.FieldLevel) bool {
    return fl.Field().Int()%2 == 0
})

type Request struct {
    Value int64 `json:"value" validate:"is-even"`
}

Returns nil if you swapped in a custom validator via SetValidator.

Custom Validator ​

Swap in any validator by implementing the interface:

go
type CustomValidator struct {
    validator *validator.Validate
}

func (cv *CustomValidator) Validate(i any) error {
    return cv.validator.Struct(i)
}

r.SetValidator(&CustomValidator{
    validator: validator.New(),
})

Pass nil to disable validation entirely:

go
r.SetValidator(nil)

Supported Validators ​

TagRule
requiredField must be non-zero
min=NMinimum length/value
max=NMaximum length/value
emailFast regex email check
gte=NGreater than or equal
lte=NLess than or equal
len=NExact length

Released under the MIT License.