API Reference

validator

Go struct validation using tags with hundreds of built-in rules, nested checks, and custom validators.

Official Documentation ↗
CompatibilityThis documentation covers version v10. Check the official docs for the latest API surface.

Installation

gogo get github.com/go-playground/validator/v10

Methods

Go struct validation using tags with hundreds of built-in rules, nested checks, and custom validators.

Overview

validator checks structs declaratively: validate tags name the rules, and one Struct call walks the type, applying built-ins like required, email, min, gte, uuid4, dive for collections, and recursion through nested structs.

Failures arrive as a typed ValidationErrors list carrying field, tag, and parameter, ready for mapping into API messages. Custom rules slot in through RegisterValidation, and the same engine powers binding in the Gin framework.

Core Methods

The most frequently used entry points, with signatures and runnable examples:

  • validate.Struct — Validates a struct against its validate tags, recursing into nested structs and pointers.
  • ValidationErrors — The typed error containing one FieldError per failed rule with field, tag, and parameter.
  • nested validation / dive — Structs validate their nested fields automatically; dive applies rules to each slice element.
  • RegisterValidation — Adds a project-specific rule callable through its own tag in struct definitions.

Usage Notes

  • Validate at the boundary, request DTOs and config structs, before business logic sees data.
  • Keep tags small and composable; push cross-field rules into custom validators.
  • Return field-level errors from ValidationErrors so clients can map them onto forms.

Common Pitfalls

  • Missing required makes other rules no-ops on zero values, silently passing bad input.
  • Errors.As into ValidationErrors, a bare type assertion panics on other error types.
  • dive validates elements but not nilness; pair with required to reject empty slices.

FAQ

Why does my struct validate as passing with zero values?
By default a field without a required-like tag is not validated at all, so a zero string passes email only when required is also present. WithRequiredStructEnabled tightens this by validating struct fields that are non-optional, matching stricter expectations.
How do I translate errors for users?
Loop ValidationErrors and map FieldError.Tag to your own messages, or use the companion universal-translator package with locale-aware messages. Tag plus Param is enough to build precise hints.
How does Gin relate to this package?
Gin embeds validator/v10 and exposes it as binding.Validator, applying validate tags during ShouldBind. You can swap or configure that validator, for custom rules or WithRequiredStructEnabled, through the engine.