Validating Go Struct Fields with go-playground/validator
Integrate the library into you're project:
go get github.com/go-playground/validator/v10
Define a struct and annotate fields with validation rules. The following snippet creates a User struct and requires the Name field to be non‑empty.
package main
import (
"log"
"github.com/go-playground/validator/v10"
)
type User struct {
Name string `validate:"required"`
}
func main() {
v := validator.New()
u := User{Name: "Alice"}
if err := v.Struct(u); err != nil {
log.Fatalf("validation issue: %s", err)
}
log.Println("struct valid")
}
Tag Composition Rules
- Comma (
,) – Separates multiple rules; validated left to right. No spaces around the comma. - Dash (
-) – Excludes the field from validation entirely. - Pipe (
|) – Acts as an OR condition; at least one rule must pass.
Common Valiadtion Attributes
Universal
required– Rejects the field's zero value.omitempty– Skips subsequent checks when the field holds its zero value.
Strings
min=n,max=n,len=n– Length constraints.alpha,alphanum,numeric– Character set restrictions.email,url,uuid– Well‑known formats.datetime=format– Time format match, e.g.,datetime=2006-01-02.eq=value,ne=value– Equality comparisons (no quotes needed).oneof=opt1 opt2 opt3– Allowed values.contains=sub,excludes=sub,startswith=pref,endswith=suf– Substring tests.
Numbers
gt=n,gte=n,lt=n,lte=n– Relational comparisons.eq=n,ne=n– Equality checks.oneof=v1 v2 v3– Enumerated values.
Slices & Arrays
min=n,max=n,len=n– Length boundaries.unique– Enforces distinct elements.
Maps
- Surround key rules with
keys/endkeys. Combine withdivefor deep validation. Example:dive,keys,min=1,max=100,endkeys,required,gt=0
Deep Validation (dive)
- Instructs the validator to inspect elements inside slices, arrays, and maps.
- For a
[]stringfield:validate:"dive,min=2"ensures each string has at least two characters. - For a
[]Structfield:validate:"dive"evaluates struct-level tags automatically (no extradiveneeded for nested structs). - Use
structonlyon the parent field to bypass child struct validation.
Cross‑Field Comparisons
eqfield=OtherField– Values must be equal.nefield=OtherField– Values must differ.gtefield=OtherField,ltefield=OtherField– Ordering constraints.
Example of cross‑field usage:
type Range struct {
Start int `validate:"ltefield=End"`
End int
}