Data Validation in Go with go-playground/validator
In modern Go (Golang) development, validating incoming data is a critical step in processing requests, forms, or configurations. The go-playground/validator library is the de facto standard for validating structs, fields, and complex nested objects. It provides a powerful set of rules (tags) for validation, supports custom error messages, internationalization, and integration with web frameworks.
Why is data validation needed?
Manually checking each field leads to code duplication and errors. validator allows you to describe rules directly in struct tags, making the code clean, declarative, and easy to maintain. You can check types, ranges, required fields, formats (email, URL, UUID), and even perform cross-field comparisons.
Installation
To install the library, run the following command in your terminal (requires Go 1.18+):
go get github.com/go-playground/validator/v10Then import the package into your code:
import "github.com/go-playground/validator/v10"Main Features
- Validation tags:
required,min,max,len,email,url,uuid,oneof, and dozens of others. - Custom validators: create your own rules using
RegisterValidation. - Nested structs: validate fields inside nested objects.
- Error messages: translations into different languages, text customization.
- Batch validation: validate arrays and slices.
Go (Golang) Code Example
package main
import ( "fmt" "github.com/go-playground/validator/v10")
// User represents a struct with validation tagstype User struct { Name string `validate:"required,min=2,max=50"` Email string `validate:"required,email"` Age int `validate:"gte=0,lte=130"` Role string `validate:"required,oneof=admin user guest"`}
func main() { validate := validator.New()
user := User{ Name: "A", Email: "invalid-email", Age: 200, Role: "superadmin", }
err := validate.Struct(user) if err != nil { for _, err := range err.(validator.ValidationErrors) { fmt.Printf("Field '%s' failed validation: %s", err.Field(), err.Tag()) } } else { fmt.Println("Data is valid!") }}When to use go-playground/validator?
This library is ideal for any Go project requiring reliable input data validation: REST APIs (with Gin, Echo, Chi), form processing, configuration files, CSV/JSON parsing. It is especially useful in microservice architecture, where each service must guarantee the correctness of incoming data.
If you need fast, flexible, and extensible validation without writing tons of conditional statements — go-playground/validator will be your best choice.