Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Validating Go Struct Fields with go-playground/validator

Tech May 8 3

Integrate the library into you're project:

go get github.com/go-playground/validator/v10

Define a struct and annotate fields with validation rules. The following snippet creates a User struct and requires the Name field to be non‑empty.

package main

import (
    "log"
    "github.com/go-playground/validator/v10"
)

type User struct {
    Name string `validate:"required"`
}

func main() {
    v := validator.New()
    u := User{Name: "Alice"}

    if err := v.Struct(u); err != nil {
        log.Fatalf("validation issue: %s", err)
    }
    log.Println("struct valid")
}

Tag Composition Rules

  • Comma (,) – Separates multiple rules; validated left to right. No spaces around the comma.
  • Dash (-) – Excludes the field from validation entirely.
  • Pipe (|) – Acts as an OR condition; at least one rule must pass.

Common Valiadtion Attributes

Universal

  • required – Rejects the field's zero value.
  • omitempty – Skips subsequent checks when the field holds its zero value.

Strings

  • min=n, max=n, len=n – Length constraints.
  • alpha, alphanum, numeric – Character set restrictions.
  • email, url, uuid – Well‑known formats.
  • datetime=format – Time format match, e.g., datetime=2006-01-02.
  • eq=value, ne=value – Equality comparisons (no quotes needed).
  • oneof=opt1 opt2 opt3 – Allowed values.
  • contains=sub, excludes=sub, startswith=pref, endswith=suf – Substring tests.

Numbers

  • gt=n, gte=n, lt=n, lte=n – Relational comparisons.
  • eq=n, ne=n – Equality checks.
  • oneof=v1 v2 v3 – Enumerated values.

Slices & Arrays

  • min=n, max=n, len=n – Length boundaries.
  • unique – Enforces distinct elements.

Maps

  • Surround key rules with keys / endkeys. Combine with dive for deep validation. Example: dive,keys,min=1,max=100,endkeys,required,gt=0

Deep Validation (dive)

  • Instructs the validator to inspect elements inside slices, arrays, and maps.
  • For a []string field: validate:"dive,min=2" ensures each string has at least two characters.
  • For a []Struct field: validate:"dive" evaluates struct-level tags automatically (no extra dive needed for nested structs).
  • Use structonly on the parent field to bypass child struct validation.

Cross‑Field Comparisons

  • eqfield=OtherField – Values must be equal.
  • nefield=OtherField – Values must differ.
  • gtefield=OtherField, ltefield=OtherField – Ordering constraints.

Example of cross‑field usage:

type Range struct {
    Start int `validate:"ltefield=End"`
    End   int
}
Tags: goValidation

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.