Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 39 ยท Binding and Validation

Validation Rules in Gin

Validate request data in Gin with the binding struct tag and rules required, min, max, len, email, oneof, gte, nested structs, slices and dive. Includes a runnable tag-validator stand-in written in plain Go.

Binding tells you what the client sent. Validation tells you whether it is acceptable. Gin uses the popular go-playground/validator library: you write rules in a binding struct tag, and every ShouldBind... call checks them after decoding. A request that breaks a rule comes back as an error before your handler touches the data.

Validation is your first line of defense, but it does not replace checks that need the database (is this email already taken?) or authorization. Think of it as a cheap, declarative filter for shape and range. This lesson assumes you know binding and the other binders, and leads to friendly error messages.

Gin does not run on this site, so the Gin snippets are read-only. The stand-ins implement a few validator rules in plain Go so you can experiment with the same ideas.

The binding tag

Go
type CreateUser struct {
	Name     string `json:"name"     binding:"required,min=2,max=50"`
	Email    string `json:"email"    binding:"required,email"`
	Age      int    `json:"age"      binding:"gte=13,lte=120"`
	Role     string `json:"role"     binding:"omitempty,oneof=reader editor admin"`
	Password string `json:"password" binding:"required,min=8"`
}

func createUser(c *gin.Context) {
	var in CreateUser
	if err := c.ShouldBindJSON(&in); err != nil {
		c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})
		return
	}
	// in is decoded AND valid here
}

Rules are separated by commas and checked left to right; the first failing rule for a field stops that field. | inside a rule means "or" (binding:"email|url").

The rules you will use most

Rule Meaning
required Value must not be the zero value ("", 0, false, nil, empty slice or map)
omitempty Skip all other rules when the value is empty
min=n, max=n Strings: length in characters; numbers: value; slices and maps: element count
len=n Exact length
gt, gte, lt, lte Numeric or length comparisons (also work on time.Time against now)
eq, ne Equal, not equal
oneof=a b c Value is one of the listed values (space separated)
email, url, uri Format checks
uuid, ip, ipv4, hostname Identifier formats
alpha, alphanum, numeric Character classes
startswith=, endswith=, contains= String checks
eqfield=Other, nefield=Other Compare to another field (password confirmation)

The email rule checks a reasonable syntax, not that the mailbox exists. The only real test of an address is sending a message to it.

required and zero values

required fails on the zero value, which has a surprising consequence for numbers and booleans:

Go
type Review struct {
	Stars  int  `json:"stars"  binding:"required"`   // 0 is rejected!
	Public bool `json:"public" binding:"required"`   // false is rejected!
}

If 0 or false are legitimate answers, use a pointer, which makes required mean "present":

Go
type Review struct {
	Stars  *int  `json:"stars"  binding:"required,gte=0,lte=5"`
	Public *bool `json:"public" binding:"required"`
}

Now a missing stars fails, while "stars": 0 passes the required check and is then tested with gte=0.

Optional fields: omitempty

Use omitempty when a field is optional but must be valid if given:

Go
Website string `json:"website" binding:"omitempty,url"`

Without omitempty an empty string would fail the url rule even though the field is optional.

Nested structs, slices and dive

Validation descends into nested structs automatically. For slices and maps you must say so with dive:

Go
type Address struct {
	City string `json:"city" binding:"required"`
	Zip  string `json:"zip"  binding:"required,len=5,numeric"`
}

type Order struct {
	Shipping Address  `json:"shipping"`
	Items    []Item   `json:"items"    binding:"required,min=1,dive"`
	Coupons  []string `json:"coupons"  binding:"omitempty,max=3,dive,alphanum,len=8"`
}

Rules before dive apply to the slice itself (at least one item, at most three coupons); rules after it apply to each element (every coupon is 8 letters or digits). Pointers to structs (*Address) are validated only when they are not nil; add required to demand them.

Comparing fields

Go
type Register struct {
	Password string `json:"password"         binding:"required,min=8"`
	Confirm  string `json:"password_confirm" binding:"required,eqfield=Password"`
	Start    time.Time `json:"start" binding:"required"`
	End      time.Time `json:"end"   binding:"required,gtfield=Start"`
}

eqfield and gtfield refer to the Go field name, not the JSON name. Cross-field rules like "end after start" are a classic use.

Stand-in: a mini validator

The following runnable program implements required, min, max, oneof and email (a simplified check) by reading the binding tag with reflection, the same technique the real library builds on. It validates three inputs and prints one message per failing field.

Go Stand-in: validating a struct from its tags

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The first user passes. The second fails four rules at once, and the third shows required and lte firing. Note how Role on the first and third inputs is accepted because omitempty skips the oneof check for an empty value.

Stand-in: pointer fields and required

This second program demonstrates the zero-value trap from earlier. Which struct accepts a rating of 0?

Go Stand-in: required on zero values versus pointers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

For {"stars":0} the plain int is indistinguishable from "missing", but the pointer sees the difference. That is why optional-but-meaningful zeros need pointer fields.

Where validation belongs

  • Put structure and range rules in tags: lengths, formats, enumerations.
  • Put rules needing data (unique email, stock available) in the service layer and return 409 Conflict or 422 from there.
  • Validate on the server even when the front end validates too. Anyone can call your API directly.
  • Keep input structs separate from models so each operation can carry its own rules (an update may allow omitting fields that a create requires).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A JSON field Stars int has binding:"required". The client sends {"stars":0}. What happens?

    required rejects zero values. Use *int when zero is a legitimate answer.
  2. 2. What does omitempty do in a binding tag?

    With omitempty an absent value is accepted, but a present value must still satisfy the other rules.
  3. 3. How do you validate every element of a []string field?

    Rules before dive apply to the slice; rules after dive are applied to each element.
  4. 4. How is oneof written for the values reader, editor and admin?

    Values after oneof= are separated by spaces, because commas separate rules.
  5. 5. Which check should NOT rely on tags alone?

    Uniqueness needs the database (and a unique index); tags validate only the shape of the input.

Summary

  • Validation rules live in the binding tag and run during ShouldBind....
  • Learn required, omitempty, min/max, gte/lte, oneof, email, url, eqfield.
  • Use pointer fields when zero is valid; use dive for slices and maps.
  • Tags check shape and range; database-dependent rules belong in the service layer.
  • Always validate on the server.

Next: Custom Validators and Friendly Error Messages registers your own rules and turns raw errors into helpful JSON.