Data Validation in Go (Golang): Libraries and Practical Examples
Data validation is one of the key aspects of developing reliable web applications and APIs in Go. Without proper validation of incoming data, an application becomes vulnerable to errors, incorrect input, and attacks. In this article, we will look at three popular libraries for validation in Go: go-playground/validator, ozzo-validation, and govalidator, and also analyze examples of their use.
Why is validation needed in Go?
Go is a strongly typed language, but this does not protect against logical errors in data: empty strings, invalid emails, numbers outside an acceptable range. Validation allows you to:
- Guarantee data integrity at the input;
- Simplify error handling;
- Increase application security;
- Reduce the amount of boilerplate code.
1. go-playground/validator — The Gold Standard
The most popular library (over 15k stars on GitHub). It allows you to describe validation rules directly in struct tags.
Installation
go get github.com/go-playground/validator/v10Basic Example
package main
import ( "fmt" "github.com/go-playground/validator/v10")
type User struct { Name string `validate:"required,min=3,max=50"` Email string `validate:"required,email"` Age int `validate:"gte=18,lte=120"`}
func main() { validate := validator.New() user := User{ Name: "A", Email: "invalid-email", Age: 15, } err := validate.Struct(user) if err != nil { for _, err := range err.(validator.ValidationErrors) { fmt.Printf("Field: %s, Error: %s", err.Field(), err.Tag()) } }}Custom Validators
validate.RegisterValidation("is-valid-username", func(fl validator.FieldLevel) bool { return len(fl.Field().String()) >= 5})
type Login struct { Username string `validate:"required,is-valid-username"`}2. ozzo-validation — Flexibility and Readability
The ozzo-validation library offers a fluent interface for building rules. It is well suited for complex business rules.
Installation
go get github.com/go-ozzo/ozzo-validation/v4Usage Example
package main
import ( "fmt" validation "github.com/go-ozzo/ozzo-validation/v4" "github.com/go-ozzo/ozzo-validation/v4/is")
type Order struct { ProductID string Quantity int Email string}
func (o Order) Validate() error { return validation.ValidateStruct(&o, validation.Field(&o.ProductID, validation.Required, validation.Length(5, 20)), validation.Field(&o.Quantity, validation.Required, validation.Min(1), validation.Max(100)), validation.Field(&o.Email, validation.Required, is.Email), )}
func main() { order := Order{ProductID: "AB", Quantity: 0, Email: "bad"} err := order.Validate() if err != nil { fmt.Println(err) }}Features
- No tags — rules are written in code;
- Easy integration with custom types;
- Support for conditional validation.
3. govalidator — Simplicity for Small Projects
A lightweight library with a set of ready-made functions for validating strings, numbers, and structs.
Installation
go get github.com/asaskevich/govalidatorExample
package main
import ( "fmt" "github.com/asaskevich/govalidator")
func main() { // String validation fmt.Println(govalidator.IsEmail("test@example.com")) // true fmt.Println(govalidator.IsURL("https://pythonlib.ru")) // true fmt.Println(govalid Also in library
Creating CLI Applications in TypeScript: Overview of Frameworks and Tools
Node.js Monitoring: Tools and Libraries for Observability
Monitoring PHP Applications with PHPMetrics
Working with XML in Go: encoding/xml, libraries and examples
Redis client for C# (.NET): StackExchange.Redis — connection and examples