API Reference

go-playground/validator

Struct and field validation library for Go driven by struct tags with custom rules and messages.

Official Documentation ↗
CompatibilityThis documentation covers version validator/v10 v10.22 / Go 1.20+. Check the official docs for the latest API surface.

Installation

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

Methods

Overview

The validator library validates Go structs using field tags, covering common rules such as required, ranges, formats and cross-field comparisons, with support for custom validators.

Core Methods

Create a validator, tag fields, and call Struct. A validation error exposes per-field failures through ValidationErrors. RegisterValidation adds custom tags, and translations localize messages.

Usage Notes

Define validation on request DTOs, translate errors into a consistent API response, and reuse a single validator instance for performance since it caches struct metadata.

Common Pitfalls

Creating a new validator per call re-parses struct metadata and is slow. Raw error strings are not user friendly, so map them to messages. Zero values can trip patterns, so use omitempty deliberately.

FAQ

How do I customize error messages?
Register translations for the default error messages and derive per-field strings from ValidationErrors, or write your own mapping keyed by field and tag.
Does it validate nested and slice fields?
Yes, with dive for slices and automatic traversal of nested structs, so you can express deep validation rules in a single tag chain.
How do I validate pointers and optional fields?
Use omitempty or omitnil so optional fields skip validation when empty, and point required rules at the underlying value.