Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Validating Go Struct Fields with go-playground/validator

Tech May 8 40

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

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...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Understanding the MP4 File Format and Analysis

Table of Contents Overview Fundamentals of the MP4 Format Key Concepts of the Container Format Box Structure Track Samples Sample Tables Chunks Detailed Explanation of Core Boxes Additional Boxes...

Leave a Comment

Anonymous

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