Exemplo
github.com/go-playground/validator/v10 v10.30.3: Validate map collection size, keys, and values independently in go-playground/validator using dive with keys and endkeys tags
Amostra verificada para golang github.com/go-playground/validator/v10 v10.30.3: Validate map collection size, keys, and values independently in…
sha256:0c54b02c2dd25ce70f00c1babd01b8a62ad115a471dd335c784e32ac86e55a59
Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu.
Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas.
MIT-0
Evidência de execução
O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.
- Base da evidência
- Contrato assinado aprovado
- Recibos de verificação
- 2
- Chaves de assinatura que o compilaram
- 2
Ambiente declarado
go linux x64 go go go
Ambientes das execuções de verificação
| Ambiente | Contrato | Etapas | Execução |
|---|---|---|---|
| go 1.26 · linux alpine/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · golang@1 |
2026-08-17 |
| go 1.26 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · golang@1 |
2026-08-18 |
Caso
HOW- Objetivo
- Validate map collection size, keys, and values independently in go-playground/validator using dive with keys and endkeys tags
- Símbolos
-
- validator.Validate
- validator.New
- Validate.Struct
- Ambiente
- go
- Criado
- 2026-08-17T18:31:54Z
Contrato
- Tags before dive validate map collection entry count, tags between keys and endkeys validate each map key, and tags after endkeys validate each map value.
- Specifying dive on a map without keys and endkeys validates map values only, leaving map keys unconstrained.
- For slice fields, tags before dive validate slice length while tags after dive validate each individual element.
Arquivos
- .gitignore
- NOTES.md
- config.go
- config_test.go
- csx.json
- go.mod
- go.sum
Código-fonte
/vendor
*.exe
*.test
# Map and Slice Collection Validation using `dive` in go-playground/validator/v10
## Search Result
An initial search of known solutions identified sample `sha256:274f2408437f66d1322945c98d90081c192c2187a49bd49dff5805e7f7795c54`, which demonstrates struct-level required validation using `WithRequiredStructEnabled()`.
This project investigates a different behavior in the library: how `dive`, `keys`, and `endkeys` tags operate on `map[K]V` and `[]T` collections to differentiate collection-level constraints from element-level and key-level constraints.
## Pinned Release
- `github.com/go-playground/validator/v10 v10.30.3`
- Go runtime: `go1.26`
## Observed Behavior and Failure Mode
When validating map and slice fields in Go structs, applying validation tags directly on the field (such as `validate:"min=2"`) validates the collection size (the number of key-value pairs or slice elements), not the contents inside the collection.
### Validating Map Keys and Values
In `go-playground/validator/v10`, validating both map keys and map values requires explicitly structuring tags around `dive`, `keys`, and `endkeys`:
- **Collection size**: Tags placed **before** `dive` (e.g. `required,min=2`) enforce the minimum number of entries in the map.
- **Map Keys**: Tags placed between `keys` and `endkeys` (e.g. `keys,min=3,endkeys`) evaluate each map key string.
- **Map Values**: Tags placed **after** `endkeys` (e.g. `required,min=5`) evaluate each map value.
### The Unvalidated Key Trap
If a developer writes `validate:"dive,min=5"` on a `map[string]string`, the validator descends directly into map **values**, leaving map **keys** completely unvalidated. Any invalid or malicious key names will silently pass validation without errors. Similarly, if `endkeys` is omitted (e.g. `validate:"dive,keys,min=3,min=5"`), all tags apply to keys rather than values.
### Slice Element Validation
For slices `[]string`, tags before `dive` (e.g. `min=2`) validate slice length, while tags after `dive` (e.g. `min=3`) evaluate each item in the slice.
package validatorcollections
import "github.com/go-playground/validator/v10"
// ServerConfig validates a map with constraints on collection count, keys, and values.
// Tags before dive validate the map collection itself (e.g. min=2 entries).
// Tags between keys and endkeys validate map keys (e.g. min=3 chars).
// Tags after endkeys validate map values (e.g. min=5 chars).
type ServerConfig struct {
Headers map[string]string `validate:"required,min=2,dive,keys,min=3,endkeys,required,min=5"`
}
// ValueOnlyConfig uses dive without keys/endkeys, which applies rules solely to map values.
type ValueOnlyConfig struct {
Headers map[string]string `validate:"dive,min=5"`
}
// SliceConfig demonstrates dive on slices: rules before dive constrain the slice length,
// while rules after dive constrain individual elements.
type SliceConfig struct {
Tags []string `validate:"required,min=2,dive,required,min=3"`
}
// NewValidator creates a standard validator instance.
func NewValidator() *validator.Validate {
return validator.New()
}
package validatorcollections_test
import (
"testing"
"github.com/go-playground/validator/v10"
"sample"
)
func TestMapValidation_FullKeysAndValues(t *testing.T) {
v := validatorcollections.NewValidator()
// Case 1: Map has too few entries (< 2) -> fails on collection size
cfgTooFew := validatorcollections.ServerConfig{
Headers: map[string]string{
"host": "server.example.com",
},
}
err := v.Struct(cfgTooFew)
if err == nil {
t.Fatal("expected error for map with count < 2, got nil")
}
valErrs, ok := err.(validator.ValidationErrors)
if !ok || len(valErrs) != 1 || valErrs[0].Field() != "Headers" || valErrs[0].Tag() != "min" {
t.Fatalf("expected 1 error on Headers with tag 'min', got: %v", err)
}
// Case 2: Map has 2 entries, but one key is too short (< 3 chars: "to")
cfgShortKey := validatorcollections.ServerConfig{
Headers: map[string]string{
"host": "server.example.com",
"to": "recipient.example.com",
},
}
err = v.Struct(cfgShortKey)
if err == nil {
t.Fatal("expected error for short map key 'to', got nil")
}
valErrs = err.(validator.ValidationErrors)
if len(valErrs) != 1 || valErrs[0].Tag() != "min" {
t.Fatalf("expected 1 error with tag 'min' on key, got: %v", err)
}
if valErrs[0].Namespace() != "ServerConfig.Headers[to]" {
t.Fatalf("expected namespace 'ServerConfig.Headers[to]', got %s", valErrs[0].Namespace())
}
// Case 3: Map has 2 entries, but one value is too short (< 5 chars: "api")
cfgShortValue := validatorcollections.ServerConfig{
Headers: map[string]string{
"host": "server.example.com",
"path": "api",
},
}
err = v.Struct(cfgShortValue)
if err == nil {
t.Fatal("expected error for short map value 'api', got nil")
}
valErrs = err.(validator.ValidationErrors)
if len(valErrs) != 1 || valErrs[0].Tag() != "min" {
t.Fatalf("expected 1 error on value with tag 'min', got: %v", err)
}
if valErrs[0].Namespace() != "ServerConfig.Headers[path]" {
t.Fatalf("expected namespace 'ServerConfig.Headers[path]', got %s", valErrs[0].Namespace())
}
// Case 4: Valid map where entry count >= 2, all keys >= 3 chars, and all values >= 5 chars
cfgValid := validatorcollections.ServerConfig{
Headers: map[string]string{
"host": "server.example.com",
"auth": "bearer-token-12345",
},
}
if err := v.Struct(cfgValid); err != nil {
t.Fatalf("expected valid map to pass, got: %v", err)
}
}
func TestMapValidation_DiveWithoutKeysValidatesOnlyValues(t *testing.T) {
v := validatorcollections.NewValidator()
// When dive is used without keys/endkeys, 1-char key 'a' passes, but short value 'tiny' (< 5) fails
cfg := validatorcollections.ValueOnlyConfig{
Headers: map[string]string{
"a": "tiny",
},
}
err := v.Struct(cfg)
if err == nil {
t.Fatal("expected validation error on short value 'tiny', got nil")
}
valErrs, ok := err.(validator.ValidationErrors)
if !ok || len(valErrs) != 1 || valErrs[0].Tag() != "min" {
t.Fatalf("expected 1 error on value, got: %v", err)
}
// 1-char key 'a' with valid value (>= 5 chars) passes because keys are unconstrained
cfgPass := validatorcollections.ValueOnlyConfig{
Headers: map[string]string{
"a": "valid-value",
},
}
if err := v.Struct(cfgPass); err != nil {
t.Fatalf("expected 1-char key to pass when keys are not validated, got: %v", err)
}
}
func TestSliceValidation_DiveDistinguishesSliceVsElementConstraints(t *testing.T) {
v := validatorcollections.NewValidator()
// Too few slice items (< 2) fails slice-level min rule
cfgFew := validatorcollections.SliceConfig{
Tags: []string{"golang"},
}
err := v.Struct(cfgFew)
if err == nil {
t.Fatal("expected error on slice length < 2, got nil")
}
valErrs, ok := err.(validator.ValidationErrors)
if !ok || len(valErrs) != 1 || valErrs[0].Field() != "Tags" || valErrs[0].Tag() != "min" {
t.Fatalf("expected 1 error on Tags:min, got: %v", err)
}
// 2 items, but one element is too short (< 3 chars: "go")
cfgShortElem := validatorcollections.SliceConfig{
Tags: []string{"golang", "go"},
}
err = v.Struct(cfgShortElem)
if err == nil {
t.Fatal("expected error on element 'go', got nil")
}
valErrs = err.(validator.ValidationErrors)
if len(valErrs) != 1 || valErrs[0].Namespace() != "SliceConfig.Tags[1]" {
t.Fatalf("expected error on Tags[1], got %v", valErrs)
}
// Valid slice with 2 items, both >= 3 chars
cfgValid := validatorcollections.SliceConfig{
Tags: []string{"golang", "validator"},
}
if err := v.Struct(cfgValid); err != nil {
t.Fatalf("expected valid slice to pass, got: %v", err)
}
}
{"case":{"believed":"A validation tag placed on a map field or after dive validates both map keys and map values, or applying min on a map validates element length rather than map entry count.","caseId":"case:sha256:df167831912e4364da377e8126f672865f733fe0c89295ca00ed5cc8cafb0de4","contract":["Tags before dive validate map collection entry count, tags between keys and endkeys validate each map key, and tags after endkeys validate each map value.","Specifying dive on a map without keys and endkeys validates map values only, leaving map keys unconstrained.","For slice fields, tags before dive validate slice length while tags after dive validate each individual element."],"goal":"Validate map collection size, keys, and values independently in go-playground/validator using dive with keys and endkeys tags","kind":"HOW","packages":["pkg:golang/github.com/go-playground/validator/v10@10.30.3"],"schemaVersion":1,"symbols":["validator.Validate","validator.New","Validate.Struct"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","ecosystem":"golang","executionContext":"go","language":"go","os":"linux","packageManager":"go","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/github.com/go-playground/validator/v10@10.30.3"],"schemaVersion":1,"symbols":["validator.Validate","validator.New","Validate.Struct"],"verifierAdapter":"golang@1"}
module sample
go 1.26.5
require github.com/go-playground/validator/v10 v10.30.3
require (
github.com/gabriel-vasile/mimetype v1.4.13 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
golang.org/x/crypto v0.52.0 // indirect
golang.org/x/sys v0.45.0 // indirect
golang.org/x/text v0.37.0 // indirect
)
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gabriel-vasile/mimetype v1.4.13 h1:46nXokslUBsAJE/wMsp5gtO500a4F3Nkz9Ufpk2AcUM=
github.com/gabriel-vasile/mimetype v1.4.13/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.30.3 h1:4MU6YkEwx7GbcPJOZxrtbu+QfF3pJLJuaYTeAH0DYy8=
github.com/go-playground/validator/v10 v10.30.3/go.mod h1:4Axh7oCNGcoGkqLoE4YWt6n20mcEIsPRlB7vPk3lpyc=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988=
golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc=
golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=