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.

GoForm Validation

Code

snippet
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/v10 as 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

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.