Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 39 ยท Binding and Validation

Custom Validators and Friendly Error Messages in Gin

Register custom validation rules in Gin, read validator.ValidationErrors, turn them into field-level JSON messages, validate by hand with struct-level checks, and try a runnable registry stand-in.

Built-in rules cover the common cases, but every application has its own: a username that may not contain spaces, a slug in a specific format, a start date that must be before the end date. And the default error text from a failed binding (Key: 'CreateUser.Email' Error:Field validation for 'Email' failed on the 'email' tag) is useless to a person filling in a form. This lesson shows how to register custom rules and how to turn the library's errors into clean, field-by-field JSON.

It follows Validation Rules; once your errors look good, middleware is the next chapter.

Gin cannot run on this site, so the Gin and validator code below is read-only. The runnable stand-ins reproduce the registry and error translation in plain Go.

Registering a custom rule

Gin exposes its validator engine through the binding package. You register a function under a tag name once, usually in main before the router starts:

Go
import (
	"regexp"

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

var slugRE = regexp.MustCompile(`^[a-z0-9]+(?:-[a-z0-9]+)*$`)

func slug(fl validator.FieldLevel) bool {
	return slugRE.MatchString(fl.Field().String())
}

func main() {
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		_ = v.RegisterValidation("slug", slug)
	}
	r := gin.Default()
	// ...
}

Now slug is usable like any built-in:

Go
type CreatePost struct {
	Title string `json:"title" binding:"required"`
	Slug  string `json:"slug"  binding:"required,slug"`
}

The function receives a validator.FieldLevel. Useful methods are Field() (the value as a reflect.Value), Param() (the text after = in the tag, so binding:"multiple_of=5" gives "5"), Parent() and GetStructFieldOK() for comparing against sibling fields.

A rule with a parameter:

Go
func multipleOf(fl validator.FieldLevel) bool {
	n, err := strconv.Atoi(fl.Param())
	if err != nil || n == 0 {
		return false
	}
	return fl.Field().Int()%int64(n) == 0
}

Keep rules pure: no database calls, no network, no global state. They run on every request and must be fast and deterministic. A uniqueness check belongs in the service layer.

Struct-level validation

When a rule involves several fields, register a struct-level validator:

Go
func dateRange(sl validator.StructLevel) {
	b := sl.Current().Interface().(Booking)
	if !b.End.After(b.Start) {
		sl.ReportError(b.End, "End", "end", "after_start", "")
	}
}

v.RegisterStructValidation(dateRange, Booking{})

ReportError adds a failure for the named field, so it shows up in the error list just like a tag failure. For a simple "end after start" you can also use gtfield=Start on the field and skip the code.

What the error really is

When binding fails because of validation, the returned error is a validator.ValidationErrors, a slice of FieldError. Everything you need is available with errors.As:

Go
var ve validator.ValidationErrors
if errors.As(err, &ve) {
	for _, fe := range ve {
		fmt.Println(fe.Field(), fe.Tag(), fe.Param(), fe.Value())
	}
}
Method Example for Age int binding:"gte=13" sent as 9
Field() Age
Tag() gte
Param() 13
Value() 9
Kind() int

A JSON syntax error is a different type (*json.SyntaxError or *json.UnmarshalTypeError), so test for the validation case first and fall back to a generic "invalid body" message.

Friendly messages

Translate each FieldError into a sentence. A switch on Tag() is enough for most apps:

Go
type FieldProblem struct {
	Field   string `json:"field"`
	Message string `json:"message"`
}

func message(fe validator.FieldError) string {
	switch fe.Tag() {
	case "required":
		return "is required"
	case "email":
		return "must be a valid email address"
	case "min":
		return "must be at least " + fe.Param()
	case "max":
		return "must be at most " + fe.Param()
	case "oneof":
		return "must be one of: " + fe.Param()
	case "slug":
		return "may contain only lowercase letters, digits and single hyphens"
	}
	return "is invalid"
}

func problems(err error) []FieldProblem {
	var ve validator.ValidationErrors
	if !errors.As(err, &ve) {
		return nil
	}
	out := make([]FieldProblem, 0, len(ve))
	for _, fe := range ve {
		out = append(out, FieldProblem{Field: fe.Field(), Message: message(fe)})
	}
	return out
}

To report the JSON name (email) instead of the Go name (Email), teach the validator to read the json tag once at startup:

Go
v.RegisterTagNameFunc(func(f reflect.StructField) string {
	name, _, _ := strings.Cut(f.Tag.Get("json"), ",")
	if name == "-" {
		return ""
	}
	return name
})

Then the handler answers with a stable shape:

Go
if err := c.ShouldBindJSON(&in); err != nil {
	if p := problems(err); p != nil {
		c.JSON(http.StatusUnprocessableEntity, gin.H{
			"error": gin.H{"code": "validation_failed", "details": p},
		})
		return
	}
	c.JSON(http.StatusBadRequest, gin.H{"error": gin.H{"code": "bad_json"}})
	return
}

This matches the error envelope from HTTP Status Codes and Error Responses. For other languages, the universal-translator package adds full translations; for most APIs a small switch like this one is clearer.

Stand-in: a rule registry

This runnable program re-creates the idea of RegisterValidation: a map from tag name to function, a field list, and a translator that produces {field, message} objects. The custom rules slug and multiple_of are registered exactly like Gin users would.

Go Stand-in: custom rules and field-level messages

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The second input produces exactly the shape you would send from Gin: a stable error code and a list of field messages a front end can attach to input boxes.

Stand-in: struct-level rule

Cross-field rules are easiest to read as ordinary functions. This stand-in validates a booking where the end must come after the start and the stay must not exceed 14 nights.

Go Stand-in: validating relations between fields

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Practical advice

  • Return all failing fields at once so users fix the form in one pass; the validator already collects them.
  • Keep messages stable and specific, and keep machine-readable codes separate from human text. Front ends may translate the text but can rely on the codes.
  • Test the translation function with table tests; it is plain Go and very quick to test.
  • Do not echo submitted passwords or secrets back in error details.
  • Register rules once at startup, never inside a handler: the engine is shared and registering per request is a data race.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where do you register a custom validation rule for Gin?

    The validator engine is shared; register rules once before serving requests.
  2. 2. What type does errors.As need to detect a validation failure?

    Validation failures are a slice of FieldError wrapped in validator.ValidationErrors.
  3. 3. In binding:"multiple_of=5", how does the rule function read the 5?

    Param returns the text after the equals sign in the tag.
  4. 4. Why should custom rules avoid database calls?

    Rules should be fast and pure. Check uniqueness in a service and return 409 or 422.

Summary

  • Register custom rules with RegisterValidation once at startup; use Param() for arguments.
  • Use RegisterStructValidation (or gtfield/eqfield) for cross-field rules.
  • errors.As(err, &validator.ValidationErrors{}) reveals field, tag, param and value.
  • Translate errors into a {field, message} list inside one stable error envelope.
  • Register a tag-name function so messages use JSON names.

Next: Middleware Basics starts the chapter on code that runs around every request.