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())
}
}
}How the snippet works
Go Form Validation with Struct Tags reduces to the function main.
for _, e := range err.(validator.ValidationErrors) is the loop that carries the per-item work. Nothing falls through silently — 1 checkpoint test err != nil on the way through.
Caveats
- Requires
github.com/go-playground/validator/v10as a package; the snippet will not run without it.
Applying it
Running the file prints labeled results such as Field — each operation’s effect is visible in the output.
Statements that matter most here
for _, e := range err.(validator.ValidationErrors) {
fmt.Printf("Field %s failed: %s\n", e.Field(), e.Tag())
}
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Do I need to install anything before running this?
- Yes: `github.com/go-playground/validator/v10` must be present in the project or the import fails at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.