Gin foundations · 5 MIN READ

Custom validators in Gin: register domain rules once and return field errors clients can rely on

Register a custom tag and a struct-level rule on Gin's validator, validate slice elements with dive and convert validator errors into a stable field-level JSON response.

Gin's binding tags cover shape: required, lengths, ranges, enumerations. Real input also has domain rules, such as a SKU format or an address that is required unless the customer picks the order up. Gin's validator accepts both kinds, but the default error text names Go structs and fields, which makes a poor API. This lesson adds the rules and a response format you can keep stable.

gin · A MAP OF THE IDEA

  1. Register tags at startup
  2. Report JSON field names
  3. dive into collections
  4. Map errors to field JSON

Useful when

  • Domain rules live next to the DTO and run for every binder.
  • Field, rule and param objects stay stable across refactors.

Watch out

  • Register methods are not thread-safe; finish them before serving.
  • Without dive, struct elements of a slice are never validated.

Implementation & operation cost: One setup function, one error mapper shared by all handlers and a table test per rule; registration is global, so tag names need care.

01

Gin's validator is a shared go-playground instance

binding.Validator is a package-level StructValidator. The default implementation lazily creates a go-playground/validator v10 instance with its tag name set to binding, and Engine() returns it as any. Type-assert it to *validator.Validate and you can register custom tags, struct-level rules and a tag-name function. Because the instance is global, everything you register applies to every binder in the process: ShouldBindJSON, ShouldBindQuery, ShouldBindUri and the rest. Give custom tags specific names such as sku rather than code, so two packages cannot collide.

02

An order endpoint with domain rules

The program registers a sku tag, a struct-level rule for the address and a tag-name function, then posts five orders: a valid one, one with four separate problems, one with no items, one with a wrongly typed field and one that is not JSON at all.

go
package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"net/http/httptest"
	"reflect"
	"regexp"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/validator/v10"
)

type line struct {
	SKU string `json:"sku" binding:"required,sku"`
	Qty int    `json:"qty" binding:"min=1,max=99"`
}

type order struct {
	Items   []line   `json:"items" binding:"required,min=1,max=20,dive"`
	Coupons []string `json:"coupons" binding:"max=3,dive,alphanum,len=8"`
	Pickup  bool     `json:"pickup"`
	Address string   `json:"address" binding:"max=200"`
}

var skuPattern = regexp.MustCompile(`^[A-Z]{3}-[0-9]{4}$`)

// setupValidation runs once at startup, before the engine serves requests.
func setupValidation() error {
	v, ok := binding.Validator.Engine().(*validator.Validate)
	if !ok {
		return errors.New("binding.Validator is not go-playground/validator")
	}
	v.RegisterTagNameFunc(func(f reflect.StructField) string {
		name, _, _ := strings.Cut(f.Tag.Get("json"), ",")
		if name == "-" {
			return ""
		}
		return name
	})
	if err := v.RegisterValidation("sku", func(fl validator.FieldLevel) bool {
		return skuPattern.MatchString(fl.Field().String())
	}); err != nil {
		return err
	}
	v.RegisterStructValidation(func(sl validator.StructLevel) {
		o := sl.Current().Interface().(order)
		if !o.Pickup && strings.TrimSpace(o.Address) == "" {
			sl.ReportError(o.Address, "address", "Address", "required_unless_pickup", "")
		}
	}, order{})
	return nil
}

type fieldError struct {
	Field string `json:"field"`
	Rule  string `json:"rule"`
	Param string `json:"param,omitempty"`
}

// wirePath turns "items.0.qty" from encoding/json into "items[0].qty".
func wirePath(field string) string {
	var b strings.Builder
	for i, part := range strings.Split(field, ".") {
		if _, err := strconv.Atoi(part); err == nil {
			b.WriteString("[" + part + "]")
			continue
		}
		if i > 0 {
			b.WriteByte('.')
		}
		b.WriteString(part)
	}
	return b.String()
}

func writeBindError(c *gin.Context, err error) {
	var invalid validator.ValidationErrors
	var typeErr *json.UnmarshalTypeError
	switch {
	case errors.As(err, &invalid):
		out := make([]fieldError, 0, len(invalid))
		for _, fe := range invalid {
			_, path, _ := strings.Cut(fe.Namespace(), ".")
			out = append(out, fieldError{Field: path, Rule: fe.Tag(), Param: fe.Param()})
		}
		c.JSON(http.StatusUnprocessableEntity, gin.H{"errors": out})
	case errors.As(err, &typeErr):
		c.JSON(http.StatusBadRequest, gin.H{"errors": []fieldError{{Field: wirePath(typeErr.Field), Rule: "type"}}})
	default:
		c.JSON(http.StatusBadRequest, gin.H{"error": "malformed JSON body"})
	}
}

func createOrder(c *gin.Context) {
	var in order
	if err := c.ShouldBindJSON(&in); err != nil {
		writeBindError(c, err)
		return
	}
	c.JSON(http.StatusCreated, gin.H{"lines": len(in.Items)})
}

func main() {
	gin.SetMode(gin.TestMode)
	if err := setupValidation(); err != nil {
		panic(err)
	}
	r := gin.New()
	r.POST("/orders", createOrder)

	for _, body := range []string{
		`{"items":[{"sku":"ABC-1234","qty":2}],"pickup":true}`,
		`{"items":[{"sku":"ABC-1234","qty":2},{"sku":"abc","qty":0}],"coupons":["SAVE2026","x"]}`,
		`{"items":[],"address":"1 Main St"}`,
		`{"items":[{"sku":"ABC-1234","qty":"2"}],"pickup":true}`,
		`{"items":[`,
	} {
		w := httptest.NewRecorder()
		r.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/orders", strings.NewReader(body)))
		fmt.Println(w.Code, w.Body.String())
	}
}
Read the code

RegisterTagNameFunc makes errors report JSON names, so Namespace() yields order.items[1].sku and the handler strips the leading type name. The sku function is an ordinary predicate over the field. The struct-level rule reports its own tag, required_unless_pickup, through ReportError. The second request produces four errors in struct order with element errors by index and the struct-level error last. {"items":[]} passes required, because a non-nil empty slice is not missing, and fails min=1. "qty":"2" never reaches validation: encoding/json returns an UnmarshalTypeError whose Field is items.0.qty, which wirePath rewrites as items[0].qty. A truncated body is reported as malformed JSON.

03

Register once, before serving

The validator is safe for concurrent validation, but its Register methods are documented as not thread-safe: they must all run before any validation. Call your setup from main before the server starts, or wrap it in sync.OnceValue when tests construct routers concurrently. The type assertion is worth checking rather than ignoring: if someone installs a different binding.Validator, registration should fail at startup instead of silently doing nothing. Unit-test a custom tag directly with Validate.Var, which runs one tag against one value without a request.

go
// setupOnce makes registration safe when tests build routers in parallel.
var setupOnce = sync.OnceValue(setupValidation)

func newRouter() (*gin.Engine, error) {
	if err := setupOnce(); err != nil {
		return nil, err
	}
	r := gin.New()
	r.POST("/orders", createOrder)
	return r, nil
}

// Unit-test a custom tag without HTTP:
// v.Var("ABC-1234", "sku") == nil, v.Var("abc-1234", "sku") != nil
Read the code

This fragment shows the startup guard. sync.OnceValue runs setupValidation exactly once and returns the same error to every caller, so a broken registration fails every router construction consistently. Validate.Var is the cheapest place to test the edges of the SKU pattern: case, length and separator.

04

dive, required and the zero value

Rules before dive apply to the collection, rules after dive apply to each element. Without dive the validator checks only the slice itself and never visits the elements, even when they are structs with their own binding tags, so items:[{"sku":"abc"}] would pass. Nested struct fields are validated without dive; a nil pointer to a struct is skipped unless the pointer field itself is required. Watch required on non-strings: on a slice it rejects only a nil value, so pair it with min=1, and on an int it rejects 0, which is why qty uses min=1 and reports a meaningful rule. If 0 must be distinguishable from an absent field, use a pointer such as *int.

05

A stable field-error contract

err.Error() on ValidationErrors produces text such as Key: 'order.Items[1].SKU' Error:Field validation for 'SKU' failed on the 'sku' tag. It exposes Go type names and changes when you rename a struct. Return a list of objects instead: field as the wire path with JSON names and [i] indices, rule as the tag name, which is a short machine-readable code, and param for bounds such as min=1 or len=8. Clients can map rule to a localized message, or you can use the validator's translation support on the server. Type errors from encoding/json happen before validation, so map them into the same shape. Use 422 for well-formed input that breaks a rule and 400 for input that cannot be decoded, or one status for both, but keep the convention identical across endpoints.

06

Test the rules at their edges

Table tests should hit both sides of every boundary: SKU in lower case or with three digits, quantities 0, 1, 99 and 100, zero, one, twenty and twenty-one items, a fourth coupon, a seven-character coupon, pickup false with a blank address. Assert the exact JSON body, since the order of errors is deterministic. Keep business rules that need current state, such as stock levels or coupon ownership, out of validators: they belong in the use case, after validation, as the binding-limits lesson argues.

TAKE THIS WITH YOU

Register custom tags and struct rules on binding.Validator once at startup, dive into collections explicitly, and translate ValidationErrors into field, rule and param objects that use wire names.

Check your understanding

Items []line has binding:"required,min=1" and every line struct has its own binding tags. What does adding dive change?

Go to the source

Progress stays in this browser. No account needed.