Skip to content

Latest commit

 

History

History

README.md

validation

Validate structs (tags), maps, or single fields with built-in rules and custom rules.

Install

go get github.com/fatkulnurk/foundation/validation@v0.3.0

Struct tags

type User struct {
    Name  string `json:"name" validate:"required,minlen=2,maxlen=50"`
    Email string `json:"email" validate:"required,email"`
    Age   int    `json:"age" validate:"nummin=18,nummax=120"`
}

errs := validation.ValidateStruct(user)
if errs.HasErrors() {
    fmt.Println(errs.Error())
    for _, e := range errs.ForField("email") {
        fmt.Println(e.Message)
    }
}

Error field names prefer the json tag when present.

Map and single field

errs := validation.ValidateMap(data, map[string][]validation.Rule{
    "email": {validation.Custom(func(field string, value any) *validation.Error {
        // ...
        return nil
    })},
})

err := validation.Validate("email", "bad", "required,email")

Tag rules

Canonical names and aliases:

Tag Alias Meaning
required Non-empty
strminlen=N minlen=N Min string length
strmaxlen=N maxlen=N Max string length
nummin=N min=N Min number
nummax=N max=N Max number
email Contains @ (simple check)
phone Phone format
username Username rules
password Password complexity
url URL format
date YYYY-MM-DD
alphanumeric Letters + digits
uuid UUID
json Valid JSON string
hexcolor Hex color
creditcard Luhn check
postalcode Postal code
base64 Base64
ip / ipv4 / ipv6 IP addresses

Unknown tags are ignored (no panic).

Custom rules

rule := validation.Custom(func(field string, value any) *validation.Error {
    s, _ := value.(string)
    if s != "ok" {
        return &validation.Error{Field: field, Message: "must be ok"}
    }
    return nil
})

See also