Go Form Validation with Struct Tags
Validate form data in Go using struct tags with the validator package, custom validation functions, nested struct validation, and human-readable error.
Code
package main
import (
"fmt"
"github.com/go-playground/validator/v10"
)
type LoginForm struct {
Email string `validate:"required,email"`
Password string `validate:"required,min=8"`
Age int `validate:"gte=0,lte=150"`
}
func main() {
v := validator.New()
form := LoginForm{Email: "[email protected]", Password: "secret123", Age: 25}
if err := v.Struct(form); err != nil {
for _, e := range err.(validator.ValidationErrors) {
fmt.Printf("Field %s failed: %s\n", e.Field(), e.Tag())
}
}
}