From 263a30db6ff4e8fd23c704c431261983f9d9574d Mon Sep 17 00:00:00 2001 From: Dmitri Aleksandrov Date: Mon, 19 Oct 2026 12:30:30 +0300 Subject: [PATCH 1/3] feat(shared): add Field.Or and Getter Or passes when the rules of any of the alternatives pass and reports the errors of the first one; Getter reads the value of a field without allocations, for the conditions of the rules. --- shared/field.go | 42 ++++++++++++++++++++++++++++++++++++++++++ shared/field_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+) diff --git a/shared/field.go b/shared/field.go index 29bcf9b..78fa496 100644 --- a/shared/field.go +++ b/shared/field.go @@ -167,6 +167,48 @@ func (f *Field[T]) When(cond func(ctx context.Context, value T) bool) *Field[T] }} } +// Or adds a rule that passes when the rules of any of the alternatives pass, every alternative configures its rules +// on its own field: f.Or(func(a *Field[T]) { a.As(str.Of).Email() }, func(a *Field[T]) { a.As(str.Of).URL() }). +// When no alternative passes, the errors of the first one are reported. The alternatives are checked in order +// and the next ones are skipped after one passes. A value that passes the first alternative is checked without +// allocations; the errors of the failed alternatives are built and dropped, so the next alternatives allocate them. +func (f *Field[T]) Or(alternatives ...func(alt *Field[T])) *Field[T] { + alts := make([][]checkFn[T], len(alternatives)) + for i, configure := range alternatives { + configure(&Field[T]{field: f.field, h: f.h, fields: f.fields, add: func(fn checkFn[T]) { + alts[i] = append(alts[i], fn) + }}) + } + f.add(func(ctx context.Context, h Helper, obj any, v *T, errs []Error) []Error { + n, first := len(errs), len(errs) + for i, checks := range alts { + start := len(errs) + for _, check := range checks { + errs = check(ctx, h, obj, v, errs) + } + if len(errs) == start { + clear(errs[n:start]) + return errs[:n] + } + if i == 0 { + first = len(errs) + continue + } + clear(errs[start:]) + errs = errs[:start] + } + return errs[:first] + }) + return f +} + +// Getter returns a function that reads a pointer to the value of the field of type T or *T from obj, +// a pointer to the configured struct, nil when the value is absent. Named types with the layout of T are allowed, +// it panics for other types. It reads the value without allocations, e.g. for the conditions of the rules. +func Getter[T any](field fmap.Field) func(obj any) *T { + return valueGetter[T](field) +} + // fieldSource applies checks to the struct field value read by get. // All checks of the field are registered as a single validation function, so the value is read once. func fieldSource[T any](add func(fn ValidationFn), get func(obj any) *T) func(fn checkFn[T]) { diff --git a/shared/field_test.go b/shared/field_test.go index b8d04df..b7b9e65 100644 --- a/shared/field_test.go +++ b/shared/field_test.go @@ -322,3 +322,33 @@ func TestInStruct(t *testing.T) { assert.False(t, present(&sample{})) assert.True(t, InStruct(sampleField(t, "Text"))(&sample{})) } + +func TestOr(t *testing.T) { + var r rules + notEmpty := func(v string) bool { return v != "" } + short := func(v string) bool { return len(v) < 3 } + f := NewValueField[string](sampleField(t, "Text"), pathHelper{}, sampleFields, r.add, nil) + f.Or(func(a *Field[string]) { + a.Check(func(v string) bool { return v == "a" }, "not a").Check(short, "long") + }, func(a *Field[string]) { + a.Check(func(v string) bool { return v == "b" }, "not b") + }, func(a *Field[string]) { + a.Check(func(v string) bool { return v == "c" }, "not c") + }).Check(notEmpty, "empty") + assert.Empty(t, r.validate(&sample{Text: "a"})) + assert.Empty(t, r.validate(&sample{Text: "b"}), "the second alternative") + assert.Empty(t, r.validate(&sample{Text: "c"}), "the third alternative after the failed second") + assert.Equal(t, []Error{{Location: "Text", Message: "not a", Value: "long"}, {Location: "Text", Message: "long", Value: "long"}}, + r.validate(&sample{Text: "long"}), "the errors of the first alternative") + + var req rules + NewValueField[*string](sampleField(t, "TextPtr"), pathHelper{}, sampleFields, req.add, nil).As(Deref).Or(func(a *Field[string]) { + a.Required(notEmpty, "required") + }, func(a *Field[string]) { + a.Check(notEmpty, "skipped for absent values") + }) + assert.Empty(t, req.validate(&sample{}), "an alternative without Required passes an absent value") + + assert.Equal(t, "x", *Getter[string](sampleField(t, "Inner.Text"))(&sample{Inner: &inner{Text: "x"}})) + assert.Nil(t, Getter[string](sampleField(t, "Inner.Text"))(&sample{})) +} From 963cbf3d383434deed06b3593373e956fed0b0c7 Mon Sep 17 00:00:00 2001 From: Dmitri Aleksandrov Date: Mon, 19 Oct 2026 12:30:30 +0300 Subject: [PATCH 2/3] feat: complete the rules of the tags of go-playground/validator The alternatives a|b, the conditions required_if, required_unless, required_with, required_with_all, required_without and required_without_all, dive into the elements of struct types by the tags of their type, keys and endkeys of map[string]V, gt, lt, ne, the strict and the not equal rules on fields, the new rules of strings, eq and ne of bools, gt and lt of times, omitnil, the escapes 0x2C and 0x7C. --- internal/tags/more_test.go | 277 +++++++++++++++++ internal/tags/tags.go | 590 ++++++++++++++++++++++++++++++++----- internal/tags/tags_test.go | 6 - 3 files changed, 787 insertions(+), 86 deletions(-) create mode 100644 internal/tags/more_test.go diff --git a/internal/tags/more_test.go b/internal/tags/more_test.go new file mode 100644 index 0000000..7e0d1fe --- /dev/null +++ b/internal/tags/more_test.go @@ -0,0 +1,277 @@ +package tags_test + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/assert" + + "github.com/insei/valigo" + "github.com/insei/valigo/internal/testenv" +) + +// codes returns the locations and the codes of the errors of the tags of T. +func codes[T any](t *testing.T, obj *T) []string { + t.Helper() + v := valigo.New() + valigo.Configure[T](v, func(b valigo.Configurator[T], _ *T) { b.Tags("validate") }) + var got []string + for _, err := range v.ValidateTyped(context.Background(), obj) { + got = append(got, err.Location+" "+err.Code) + } + return got +} + +type moreStrings struct { + Gt string `validate:"gt=2"` + Lt string `validate:"lt=2"` + Gte string `validate:"gte=2,lte=3"` + Ne string `validate:"ne=x"` + Old string + New string `validate:"nefield=Old"` + Alpha string `validate:"alpha"` + Number string `validate:"number"` + Numeric string `validate:"numeric"` + Hex string `validate:"hexadecimal"` + Excl string `validate:"excludes=x,containsany=0x2C;,excludesall=0x7C"` + Starts string `validate:"startsnotwith=a,endsnotwith=z"` + Fold string `validate:"eq_ignore_case=Yes"` + Contact string `validate:"email|url"` + Code string `validate:"len=2|oneof=none"` +} + +func TestMoreStrings(t *testing.T) { + valid := &moreStrings{Gt: "abc", Gte: "ab", Old: "a", New: "b", Alpha: "ab", Number: "01", Numeric: "-1.5", Hex: "0xff", + Excl: "a,b", Fold: "YES", Contact: "https://example.com", Code: "none"} + assert.Empty(t, codes(t, valid)) + valid.Contact, valid.Code = "a@b.cc", "ab" + assert.Empty(t, codes(t, valid), "the other alternatives") + + assert.Equal(t, []string{ + "Gt string.min_runes", "Lt string.max_runes", "Gte string.min_runes", "Ne value.not_equal", "New string.not_equal_field", + "Alpha string.alpha", "Number string.digits", "Numeric string.numeric", "Hex string.hexadecimal", + "Excl string.excludes", "Excl string.contains_any", "Excl string.excludes_any", + "Starts string.not_prefix", "Starts string.not_suffix", "Fold string.equal_fold", + "Contact string.email", "Code string.max_runes", + }, codes(t, &moreStrings{Gt: "ab", Lt: "ab", Gte: "a", Ne: "x", Old: "a", New: "a", Alpha: "a1", Number: "-1", Numeric: "1.", + Hex: "x", Excl: "x|", Starts: "abz", Fold: "no", Contact: "nope", Code: "abc"})) +} + +type moreNumbers struct { + Gt int `validate:"gt=1,lt=5"` + Ne uint `validate:"ne=3"` + Min float64 + Max float64 `validate:"gtfield=Min"` + Low float64 `validate:"ltfield=Min"` + Same float64 `validate:"eqfield=Min"` + Other float64 `validate:"nefield=Min"` + On bool `validate:"eq=true"` + Off bool `validate:"ne=true"` + Later time.Time `validate:"gt"` + Ago *time.Time `validate:"omitnil,lte"` +} + +func TestMoreNumbers(t *testing.T) { + past, future := time.Now().Add(-time.Hour), time.Now().Add(time.Hour) + assert.Empty(t, codes(t, &moreNumbers{Gt: 2, Min: 1, Max: 2, Low: 0, Same: 1, Other: 2, On: true, Later: future, Ago: &past})) + assert.Equal(t, []string{ + "Gt number.greater_than", "Ne value.not_equal", "Max number.greater_field", "Low number.less_field", + "Same value.equal_field", "Other value.not_equal_field", "On value.equal", "Off value.not_equal", + "Later time.in_future", "Ago time.in_past", + }, codes(t, &moreNumbers{Gt: 1, Ne: 3, Min: 1, Max: 1, Low: 1, Same: 2, Other: 1, Off: true, Later: past, Ago: &future})) + assert.Equal(t, []string{"Gt number.less_than"}, codes(t, &moreNumbers{Gt: 5, Min: 1, Max: 2, Same: 1, On: true, Later: future})[:1]) +} + +type moreLengths struct { + Gt []int `validate:"gt=1"` + Lt []int `validate:"lt=2"` + Eq map[string]int `validate:"eq=1"` + Gte *[]int `validate:"omitnil,gte=1,lte=1"` +} + +func TestMoreLengths(t *testing.T) { + one := []int{1} + assert.Empty(t, codes(t, &moreLengths{Gt: []int{1, 2}, Eq: map[string]int{"a": 1}, Gte: &one})) + assert.Equal(t, []string{"Gt slice.min_len", "Lt slice.max_len", "Eq map.min_len", "Gte slice.min_len"}, + codes(t, &moreLengths{Gt: []int{1}, Lt: []int{1, 2}, Gte: &[]int{}})) +} + +type moreConditions struct { + Kind string + Count int + Ok bool + Ptr *string + List []string + Labels map[string]string + At time.Time + If string `validate:"required_if=Kind company Count 2"` + Unless string `validate:"required_unless=Kind person"` + With string `validate:"required_with=Ptr List"` + WithAll string `validate:"required_with_all=Labels At"` + Without string `validate:"required_without=Ok Ptr"` + NoneOf string `validate:"required_without_all=Count Ok"` + Flag *int `validate:"required_if=Ok true"` + Limit *int + Note string `validate:"required_if=Limit 3"` +} + +func TestConditions(t *testing.T) { + s := "x" + assert.Equal(t, []string{"Unless string.required", "Without string.required", "NoneOf string.required"}, + codes(t, &moreConditions{}), "nothing is present") + assert.Equal(t, []string{"If string.required", "Unless string.required", "With string.required", "WithAll string.required", "Flag number.required"}, + codes(t, &moreConditions{Kind: "company", Count: 2, Ok: true, Ptr: &s, Labels: map[string]string{"a": "b"}, At: time.Now()})) + three := 3 + assert.Equal(t, []string{"Unless string.required", "Without string.required", "NoneOf string.required", "Note string.required"}, + codes(t, &moreConditions{Limit: &three}), "a pointer field is compared with its value") + one := 1 + assert.Empty(t, codes(t, &moreConditions{Kind: "person", Count: 1, Ok: true, Ptr: &s, List: []string{}, Labels: map[string]string{}, + With: "w", Flag: &one})) +} + +type moreMaps struct { + Labels map[string]string `validate:"dive,keys,alpha,endkeys,required"` + Keys map[string]int `validate:"dive,keys,max=2,endkeys"` + Values map[string]int `validate:"dive,min=1"` +} + +func TestKeys(t *testing.T) { + assert.Empty(t, codes(t, &moreMaps{Labels: map[string]string{"ab": "x"}, Keys: map[string]int{"ab": 0}, Values: map[string]int{"a": 1}})) + assert.Equal(t, []string{"Labels[a1] string.alpha", "Labels[b] string.required", "Keys[abc] string.max_runes", "Values[a] number.min"}, + codes(t, &moreMaps{Labels: map[string]string{"a1": "x", "b": ""}, Keys: map[string]int{"abc": 0}, Values: map[string]int{"a": 0}})) +} + +type moreItem struct { + Title string `validate:"required,max=3"` + Min int + Max int `validate:"gtefield=Min"` +} + +type moreNode struct { + Name string `validate:"required"` + Children []moreNode `validate:"dive"` +} + +type moreElems struct { + Items []moreItem `validate:"min=1,dive"` + Pointers []*moreItem `validate:"dive,required"` + Optional *[]*moreItem `validate:"omitempty,dive,omitempty"` + Tree moreNode +} + +func TestStructElements(t *testing.T) { + valid := &moreElems{Items: []moreItem{{Title: "a"}}, Pointers: []*moreItem{{Title: "b"}}, Optional: &[]*moreItem{nil}, + Tree: moreNode{Name: "root", Children: []moreNode{{Name: "a", Children: []moreNode{{Name: "b"}}}}}} + assert.Empty(t, codes(t, valid)) + assert.Equal(t, []string{ + "Items[1].Title string.required", "Items[2].Title string.max_runes", "Items[2].Max number.min_field", + "Pointers[0] value.required", "Pointers[1].Title string.required", + "Optional[0].Title string.required", + "Tree.Children[0].Children[0].Name string.required", + }, codes(t, &moreElems{ + Items: []moreItem{{Title: "a"}, {}, {Title: "long", Min: 2, Max: 1}}, + Pointers: []*moreItem{nil, {}}, + Optional: &[]*moreItem{{}}, + Tree: moreNode{Name: "root", Children: []moreNode{{Name: "a", Children: []moreNode{{}}}}}, + })) + + if !testenv.RaceEnabled { + v := valigo.New() + valigo.Configure[moreElems](v, func(b valigo.Configurator[moreElems], _ *moreElems) { b.Tags("validate") }) + ctx := context.Background() + assert.Zero(t, testing.AllocsPerRun(10, func() { v.ValidateTyped(ctx, valid) }), "the elements are validated without allocations") + alts := valigo.New() + valigo.Configure[moreStrings](alts, func(b valigo.Configurator[moreStrings], _ *moreStrings) { b.Tags("validate") }) + first := &moreStrings{Gt: "abc", Gte: "ab", Old: "a", New: "b", Alpha: "ab", Number: "01", Numeric: "1", Hex: "f", + Excl: ",", Fold: "yes", Contact: "a@b.cc", Code: "ab"} + assert.Zero(t, testing.AllocsPerRun(10, func() { alts.ValidateTyped(ctx, first) }), "the first alternatives pass") + } +} + +func TestMoreTagsErrors(t *testing.T) { + tests := []struct { + name string + configure func() + err string + }{ + {"condition without fields", tagsOf[struct { + A string `validate:"required_with"` + }], `valigo: tag validate:"required_with" of field A: required_with needs the fields`}, + {"required struct", tagsOf[struct { + A tagsAddress `validate:"required_with=B"` + B string + }], `valigo: tag validate:"required_with=B" of field A: the rule required isn't supported for the field, use the rules in code`}, + {"odd pairs", tagsOf[struct { + A string `validate:"required_if=B"` + B string + }], `valigo: tag validate:"required_if=B" of field A: required_if=B: the pairs of a field and a value expected`}, + {"no condition field", tagsOf[struct { + A string `validate:"required_with=B"` + }], `valigo: tag validate:"required_with=B" of field A: required_with=B: no field B`}, + {"no value field", tagsOf[struct { + A string `validate:"required_if=B 1"` + }], `valigo: tag validate:"required_if=B 1" of field A: required_if=B 1: no field B`}, + {"struct condition", tagsOf[struct { + A string `validate:"required_with=B"` + B tagsAddress + }], `valigo: tag validate:"required_with=B" of field A: required_with=B: the field B of type tags_test.tagsAddress can't be a condition`}, + {"slice value", tagsOf[struct { + A string `validate:"required_if=B x"` + B []string + }], `valigo: tag validate:"required_if=B x" of field A: required_if=B x: the field B of type []string can't be compared with a value`}, + {"time value", tagsOf[struct { + A string `validate:"required_if=B x"` + B time.Time + }], `valigo: tag validate:"required_if=B x" of field A: required_if=B x: the field B of type time.Time can't be compared with a value`}, + {"bad value", tagsOf[struct { + A string `validate:"required_if=B x"` + B int + }], `valigo: tag validate:"required_if=B x" of field A: required_if=B x: strconv.ParseInt: parsing "x": invalid syntax`}, + {"unknown condition", tagsOf[struct { + A string `validate:"required_iff=B"` + B string + }], `valigo: tag validate:"required_iff=B" of field A: the rule required_iff isn't supported for the field, use the rules in code`}, + {"condition of elements", tagsOf[struct { + A []string `validate:"dive,required_with=B"` + B string + }], `valigo: tag validate:"dive,required_with=B" of field A: required_with isn't supported for the elements`}, + {"keys without endkeys", tagsOf[struct { + A map[string]string `validate:"dive,keys,alpha"` + }], `valigo: tag validate:"dive,keys,alpha" of field A: keys without endkeys`}, + {"key rule", tagsOf[struct { + A map[string]string `validate:"dive,keys,isbn,endkeys"` + }], `valigo: tag validate:"dive,keys,isbn,endkeys" of field A: the rule isbn isn't supported for the field, use the rules in code`}, + {"unique structs", tagsOf[struct { + A []tagsAddress `validate:"unique"` + }], `valigo: tag validate:"unique" of field A: unique of the slices of structs isn't supported`}, + {"rule of struct elements", tagsOf[struct { + A []tagsAddress `validate:"dive,required"` + }], `valigo: tag validate:"dive,required" of field A: the rule required isn't supported for the field, use the rules in code`}, + {"alternative", tagsOf[struct { + A string `validate:"email|isbn"` + }], `valigo: tag validate:"email|isbn" of field A: the rule isbn isn't supported for the field, use the rules in code`}, + {"time with a parameter", tagsOf[struct { + A time.Time `validate:"gt=1"` + }], `valigo: tag validate:"gt=1" of field A: gt=1: the times are compared with the current time, without a parameter`}, + {"bad bool", tagsOf[struct { + A bool `validate:"eq=yes"` + }], `valigo: tag validate:"eq=yes" of field A: eq=yes: strconv.ParseBool: parsing "yes": invalid syntax`}, + {"bad length", tagsOf[struct { + A []string `validate:"gt=x"` + }], `valigo: tag validate:"gt=x" of field A: gt=x: strconv.Atoi: parsing "x": invalid syntax`}, + {"bad string length", tagsOf[struct { + A string `validate:"lt=x"` + }], `valigo: tag validate:"lt=x" of field A: lt=x: strconv.Atoi: parsing "x": invalid syntax`}, + {"element of a struct", tagsOf[struct { + A []struct { + B string `validate:"isbn"` + } `validate:"dive"` + }], `valigo: tag validate:"isbn" of field B: the rule isbn isn't supported for the field, use the rules in code`}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.PanicsWithValue(t, tt.err, tt.configure) + }) + } +} diff --git a/internal/tags/tags.go b/internal/tags/tags.go index 03a1a71..2068147 100644 --- a/internal/tags/tags.go +++ b/internal/tags/tags.go @@ -9,9 +9,11 @@ import ( "strconv" "strings" "time" + "unsafe" "github.com/insei/fmap/v3" + "github.com/insei/valigo/internal/zero" "github.com/insei/valigo/rules/eq" "github.com/insei/valigo/rules/num" "github.com/insei/valigo/rules/str" @@ -34,20 +36,53 @@ type Struct struct { // Apply configures the rules of the tag name of the fields of the struct and of its nested structs, // see valigo.Configurator.Tags. It panics on an unknown rule. func Apply(s Struct, name string) { + b := &builder{name: name, helper: s.Helper, structs: map[reflect.Type]*[]shared.ValidationFn{}} + b.apply(s) +} + +// builder configures the rules of the tags of a struct and of the structs of its elements. +type builder struct { + name string + helper shared.Helper + // structs are the rules of the struct types of the elements, built once: a recursive type refers to its rules + structs map[reflect.Type]*[]shared.ValidationFn +} + +func (b *builder) apply(s Struct) { for _, path := range s.Storage.GetAllPaths() { field := s.Storage.MustFind(path) - tag := field.GetTag().Get(name) + tag := field.GetTag().Get(b.name) if tag == "" || tag == "-" { continue } t := tagContext{field: field, h: s.Helper, fields: s.Fields, add: inStruct(field, s.Add), describe: s.Describe, - storage: s.Storage, model: s.Model} + storage: s.Storage, model: s.Model, b: b} if err := t.apply(parseTag(tag)); err != nil { - panic(fmt.Sprintf("valigo: tag %s:%q of field %s: %v", name, tag, path, err)) + panic(fmt.Sprintf("valigo: tag %s:%q of field %s: %v", b.name, tag, path, err)) } } } +// rulesOf returns the rules of the tags of the struct type of the elements of a slice. +func (b *builder) rulesOf(typ reflect.Type) *[]shared.ValidationFn { + if fns, ok := b.structs[typ]; ok { + return fns + } + fns := new([]shared.ValidationFn) + b.structs[typ] = fns + model := reflect.New(typ).Interface() + zero.Must(model) + storage, _ := fmap.GetFrom(model) // a pointer to a struct + b.apply(Struct{Storage: storage, Model: model, Helper: b.helper, + Fields: func(fieldPtr any) fmap.Field { + field, _ := storage.GetFieldByPtr(model, fieldPtr) // the pointers of otherField + return field + }, + Add: func(fn shared.ValidationFn) { *fns = append(*fns, fn) }, + }) + return fns +} + // inStruct skips the rules of the field when the nested struct stored by pointer, which the field is in, is nil, // like go-playground/validator does: the rules of the fields of an optional nested struct apply when it is present. func inStruct(field fmap.Field, add func(fn shared.ValidationFn)) func(fn shared.ValidationFn) { @@ -58,10 +93,14 @@ func inStruct(field fmap.Field, add func(fn shared.ValidationFn)) func(fn shared if !nested { return add } - present := shared.InStruct(field) + return when(add, shared.InStruct(field)) +} + +// when applies the rules registered by the returned function only when cond returns true for the object. +func when(add func(fn shared.ValidationFn), cond func(obj any) bool) func(fn shared.ValidationFn) { return func(fn shared.ValidationFn) { add(func(ctx context.Context, h shared.Helper, obj any, errs []shared.Error) []shared.Error { - if !present(obj) { + if !cond(obj) { return errs } return fn(ctx, h, obj, errs) @@ -74,16 +113,40 @@ type tagRule struct { name, param string } +// parseTag splits the tag to the rules, 0x2C in the parameters is a comma and 0x7C is a pipe, like in +// go-playground/validator. func parseTag(tag string) []tagRule { parts := strings.Split(tag, ",") rules := make([]tagRule, len(parts)) for i, part := range parts { + if strings.Contains(part, "|") { + // the alternatives, see alternatives + rules[i] = tagRule{name: part} + continue + } name, param, _ := strings.Cut(part, "=") - rules[i] = tagRule{name: name, param: param} + rules[i] = tagRule{name: name, param: unescape(param)} } return rules } +func unescape(param string) string { + return strings.NewReplacer("0x2C", ",", "0x7C", "|").Replace(param) +} + +// alternatives returns the rules of the alternatives of a rule with |, e.g. rgb|rgba, or false. +func (r tagRule) alternatives() ([]tagRule, bool) { + if !strings.Contains(r.name, "|") { + return nil, false + } + var alts []tagRule + for _, part := range strings.Split(r.name, "|") { + name, param, _ := strings.Cut(part, "=") + alts = append(alts, tagRule{name: name, param: unescape(param)}) + } + return alts, true +} + // tagContext is the field of the tag with the arguments of the configurators. type tagContext struct { field fmap.Field @@ -93,6 +156,7 @@ type tagContext struct { describe shared.Describe storage fmap.Storage model any + b *builder // elem is true for the rules of the elements after dive elem bool } @@ -101,10 +165,9 @@ var timeType = reflect.TypeFor[time.Time]() // apply applies the rules to the field, the rules after dive to its elements. func (t tagContext) apply(rules []tagRule) error { - for _, r := range rules { - if strings.Contains(r.name, "|") { - return errors.New("the alternatives of | aren't supported, use When or Custom") - } + rules, err := t.conditions(rules) + if err != nil { + return err } typ := t.field.GetType() ptr := typ.Kind() == reflect.Pointer @@ -126,11 +189,141 @@ func (t tagContext) apply(rules []tagRule) error { return kind.value(t, ptr, rules) } +// conditions applies the conditional rules required_if, required_unless, required_with, required_with_all, +// required_without and required_without_all, and returns the other rules. +func (t tagContext) conditions(rules []tagRule) ([]tagRule, error) { + var rest []tagRule + for i, r := range rules { + if r.name == "dive" { + // the rules of the elements, the conditions of the elements are checked by the elements + return append(rest, rules[i:]...), nil + } + if !strings.HasPrefix(r.name, "required_") { + rest = append(rest, r) + continue + } + cond, err := t.condition(r) + if err != nil { + return nil, err + } + // the conditional rules aren't described in JSON Schema + conditional := t + conditional.add, conditional.describe = when(t.add, cond), nil + if err := conditional.apply([]tagRule{{name: "required"}}); err != nil { + return nil, err + } + } + return rest, nil +} + +// condition returns the condition of a conditional rule by the values of the fields of its parameter. +func (t tagContext) condition(r tagRule) (func(obj any) bool, error) { + params := strings.Fields(r.param) + if len(params) == 0 { + return nil, fmt.Errorf("%s needs the fields", r.name) + } + switch r.name { + case "required_if", "required_unless": + if len(params)%2 != 0 { + return nil, fmt.Errorf("%s=%s: the pairs of a field and a value expected", r.name, r.param) + } + var equals []func(obj any) bool + for i := 0; i < len(params); i += 2 { + other, err := t.other(r, params[i]) + if err != nil { + return nil, err + } + eq, err := equalsOf(other, params[i+1]) + if err != nil { + return nil, fmt.Errorf("%s=%s: %w", r.name, r.param, err) + } + equals = append(equals, eq) + } + all := func(obj any) bool { + for _, eq := range equals { + if !eq(obj) { + return false + } + } + return true + } + if r.name == "required_if" { + return all, nil + } + return func(obj any) bool { return !all(obj) }, nil + case "required_with", "required_with_all", "required_without", "required_without_all": + var presents []func(obj any) bool + for _, p := range params { + other, err := t.other(r, p) + if err != nil { + return nil, err + } + present, err := presentOf(other) + if err != nil { + return nil, fmt.Errorf("%s=%s: %w", r.name, r.param, err) + } + presents = append(presents, present) + } + // with: any is present, with_all: all are present, without: any is absent, without_all: all are absent + want, all := !strings.HasPrefix(r.name, "required_without"), strings.HasSuffix(r.name, "_all") + return func(obj any) bool { + for _, present := range presents { + if present(obj) != want && all { + return false + } + if present(obj) == want && !all { + return true + } + } + return all + }, nil + } + return nil, unsupported(r) +} + +// presentOf returns whether the value of the field isn't zero: not nil, not empty, not the zero value. +func presentOf(field fmap.Field) (func(obj any) bool, error) { + typ := field.GetType() + switch typ.Kind() { + case reflect.Pointer: + get := shared.Getter[*struct{}](field) + return func(obj any) bool { p := get(obj); return p != nil && *p != nil }, nil + case reflect.Slice: + get := shared.Getter[[]struct{}](field) + return func(obj any) bool { p := get(obj); return p != nil && len(*p) > 0 }, nil + case reflect.Map: + // only the length is read, the type of the elements doesn't matter + get := shared.Getter[map[struct{}]struct{}](field) + return func(obj any) bool { p := get(obj); return p != nil && len(*p) > 0 }, nil + } + kind, ok := kinds[typ.Kind()] + if typ == timeType { + kind, ok = timeTags, true + } + if !ok { + return nil, fmt.Errorf("the field %s of type %s can't be a condition", field.GetStructPath(), typ) + } + return kind.present(field), nil +} + +// equalsOf returns whether the value of the field is equal to the parameter. +func equalsOf(field fmap.Field, param string) (func(obj any) bool, error) { + typ := field.GetType() + if typ.Kind() == reflect.Pointer { + typ = typ.Elem() + } + kind, ok := kinds[typ.Kind()] + if !ok { + return nil, fmt.Errorf("the field %s of type %s can't be compared with a value", field.GetStructPath(), field.GetType()) + } + return kind.equals(field, param) +} + // structRules applies the rules of a nested struct field: required of a pointer, the fields have their own tags. func (t tagContext) structRules(ptr bool, rules []tagRule) error { for _, r := range rules { switch { - case r.name == "omitempty": + case r.name == "omitempty" || r.name == "omitnil": case r.name == "required" && ptr: f := shared.NewValueField[*struct{}](t.field, t.h, t.fields, t.add, t.describe) f.Schema(shared.KeywordRequired, true) @@ -152,7 +345,8 @@ const ( mapMinLenKey = "validation:map:Cannot contain less than %d elements" ) -// container applies the rules of a slice or a map field, the rules after dive to its elements or values. +// container applies the rules of a slice or a map field, the rules after dive to its elements or values, +// the rules between keys and endkeys after dive to the keys of a map. func (t tagContext) container(typ reflect.Type, ptr bool, rules []tagRule) error { own, elems := rules, []tagRule(nil) for i, r := range rules { @@ -177,6 +371,12 @@ func (t tagContext) container(typ reflect.Type, ptr bool, rules []tagRule) error if elemPtr { elem = elem.Elem() } + if !isMap && elem.Kind() == reflect.Struct && elem != timeType { + if unique { + return errors.New("unique of the slices of structs isn't supported") + } + return t.structElems(ptr, elem, elemPtr, elems) + } kind, ok := kinds[elem.Kind()] if elem == timeType { kind, ok = timeTags, true @@ -187,7 +387,11 @@ func (t tagContext) container(typ reflect.Type, ptr bool, rules []tagRule) error case isMap && (typ.Key().Kind() != reflect.String || elemPtr): return errors.New("dive is supported for the maps of strings to values, map[string]V") case isMap: - return kind.values(t, elems) + keys, values, err := splitKeys(elems) + if err != nil { + return err + } + return kind.mapRules(t, keys, values) case unique && elemPtr: return errors.New("unique of the slices of pointers isn't supported") case unique: @@ -199,6 +403,82 @@ func (t tagContext) container(typ reflect.Type, ptr bool, rules []tagRule) error return kind.elems(t, elemPtr, elems) } +// splitKeys returns the rules of the keys between keys and endkeys and the rules of the values after them. +func splitKeys(rules []tagRule) (keys, values []tagRule, err error) { + if len(rules) == 0 || rules[0].name != "keys" { + return nil, rules, nil + } + for i, r := range rules { + if r.name == "endkeys" { + return rules[1:i], rules[i+1:], nil + } + } + return nil, nil, errors.New("keys without endkeys") +} + +// structElems applies the rules of the tags of the struct type of the elements of the slice field to every element, +// the location of an error is Items[1].City. The rules after dive are required and omitempty of the elements. +func (t tagContext) structElems(ptr bool, elem reflect.Type, elemPtr bool, rules []tagRule) error { + required := false + for _, r := range rules { + switch { + case r.name == "omitempty" || r.name == "omitnil": + case r.name == "required" && elemPtr: + required = true + default: + return unsupported(r) + } + } + fns, size, h, field := t.b.rulesOf(elem), elem.Size(), t.h, t.field + msg := shared.M("value.required", valueRequiredKey) + check := func(ctx context.Context, i int, p unsafe.Pointer, errs []shared.Error) []shared.Error { + n := len(errs) + if p == nil { + if !required { + return errs + } + errs = append(errs, msg.Error(ctx, h, field, nil)) + } else { + obj := reflect.NewAt(elem, p).Interface() + for _, fn := range *fns { + errs = fn(ctx, h, obj, errs) + } + } + if len(errs) == n { + return errs + } + location := h.FieldLocation(field) + "[" + strconv.Itoa(i) + "]" + for j := n; j < len(errs); j++ { + if p == nil { + errs[j].Location = location + } else { + errs[j].Location = location + "." + errs[j].Location + } + } + return errs + } + if elemPtr { + valueField[[]*struct{}](t, ptr).Custom(func(ctx context.Context, _ *shared.FieldCustomHelper, s []*struct{}) []shared.Error { + var errs []shared.Error + for i, p := range s { + errs = check(ctx, i, unsafe.Pointer(p), errs) + } + return errs + }) + return nil + } + // the elements are read by the data of the slice and the size of the element type + valueField[[]struct{}](t, ptr).Custom(func(ctx context.Context, _ *shared.FieldCustomHelper, s []struct{}) []shared.Error { + var errs []shared.Error + data := unsafe.Pointer(unsafe.SliceData(s)) + for i := range s { + errs = check(ctx, i, unsafe.Add(data, uintptr(i)*size), errs) + } + return errs + }) + return nil +} + // lenRules applies the rules of the length of a slice or a map field. func (t tagContext) lenRules(isMap, ptr bool, rules []tagRule) error { // the length is read by the header of any slice or map, the type of the elements doesn't matter; @@ -232,10 +512,20 @@ func lengthRules[C any](t tagContext, ptr bool, rules []tagRule, length func(c C return nil }) } + minLen := func(n int) { + f.Schema(m.minWord, n) + check(func(v int) bool { return v >= n }, shared.M(m.code+".min_len", m.minKey, shared.P("min", n))) + } + maxLen := func(n int) { + f.Schema(m.maxWord, n) + check(func(v int) bool { return v <= n }, shared.M(m.code+".max_len", m.maxKey, shared.P("max", n))) + } for _, r := range rules { switch r.name { - case "omitempty": - f = f.When(func(_ context.Context, c C) bool { return length(c) > 0 }) + case "omitempty", "omitnil": + if r.name == "omitempty" { + f = f.When(func(_ context.Context, c C) bool { return length(c) > 0 }) + } case "unique": if !m.unique { return unsupported(r) @@ -246,18 +536,23 @@ func lengthRules[C any](t tagContext, ptr bool, rules []tagRule, length func(c C // an absent value, the value isn't in the error f.RequiredMsg(func(C) bool { return true }, msg) check(func(n int) bool { return n > 0 }, msg) - case "min", "max", "len": + case "min", "max", "len", "eq", "gt", "gte", "lt", "lte": n, err := strconv.Atoi(r.param) if err != nil { return fmt.Errorf("%s=%s: %w", r.name, r.param, err) } - if r.name != "max" { - f.Schema(m.minWord, n) - check(func(v int) bool { return v >= n }, shared.M(m.code+".min_len", m.minKey, shared.P("min", n))) - } - if r.name != "min" { - f.Schema(m.maxWord, n) - check(func(v int) bool { return v <= n }, shared.M(m.code+".max_len", m.maxKey, shared.P("max", n))) + switch r.name { + case "min", "gte": + minLen(n) + case "gt": + minLen(n + 1) + case "max", "lte": + maxLen(n) + case "lt": + maxLen(n - 1) + default: + minLen(n) + maxLen(n) } default: return unsupported(r) @@ -280,15 +575,21 @@ type kindTags interface { value(t tagContext, ptr bool, rules []tagRule) error // elems applies the rules to the elements of the slice field elems(t tagContext, ptr bool, rules []tagRule) error - // values applies the rules to the values of the map[string]V field - values(t tagContext, rules []tagRule) error + // mapRules applies the rules to the keys and the values of the map[string]V field + mapRules(t tagContext, keys, values []tagRule) error // unique checks that the slice field has no duplicates unique(t tagContext) + // present returns whether the value of the field isn't zero + present(field fmap.Field) func(obj any) bool + // equals returns whether the value of the field is equal to the parameter + equals(field fmap.Field, param string) (func(obj any) bool, error) } -// typedTags is kindTags of the values of type V by the rules of apply. +// typedTags is kindTags of the values of type V by the rules of apply, parse parses a parameter of the conditions, +// nil for time.Time. type typedTags[V comparable] struct { apply func(t tagContext, f *shared.Field[V], optional bool, rules []tagRule) error + parse func(s string) (V, error) } func (k typedTags[V]) value(t tagContext, ptr bool, rules []tagRule) error { @@ -301,12 +602,20 @@ func (k typedTags[V]) elems(t tagContext, ptr bool, rules []tagRule) error { return k.applyValue(t, s.EachField(), ptr, rules) } -func (k typedTags[V]) values(t tagContext, rules []tagRule) error { +func (k typedTags[V]) mapRules(t tagContext, keys, values []tagRule) error { t.elem = true + m := shared.NewMapFieldConfigurator[string, V](t.field, t.h, t.fields, t.add, t.describe) var err error - shared.NewMapFieldConfigurator[string, V](t.field, t.h, t.fields, t.add, t.describe).EachValue(func(f *shared.Field[V]) { - err = k.applyValue(t, f, false, rules) - }) + if len(keys) > 0 { + m.EachKey(func(f *shared.Field[string]) { + err = stringKind.applyValue(t, f, false, keys) + }) + } + if err == nil && len(values) > 0 { + m.EachValue(func(f *shared.Field[V]) { + err = k.applyValue(t, f, false, values) + }) + } return err } @@ -314,34 +623,83 @@ func (k typedTags[V]) unique(t tagContext) { shared.NewSliceFieldConfigurator[V](t.field, t.h, t.fields, t.add, t.describe).As(eq.Slice).Unique() } -// applyValue applies the rules, omitempty skips the next rules for the zero value. +func (k typedTags[V]) present(field fmap.Field) func(obj any) bool { + get := shared.Getter[V](field) + var zero V + return func(obj any) bool { + p := get(obj) + return p != nil && *p != zero + } +} + +// equals is called for the kinds of the parameters, they have parse. +func (k typedTags[V]) equals(field fmap.Field, param string) (func(obj any) bool, error) { + value, err := k.parse(param) + if err != nil { + return nil, err + } + get := shared.Getter[V](field) + return func(obj any) bool { + p := get(obj) + return p != nil && *p == value + }, nil +} + +// applyValue applies the rules: omitempty skips the next rules for the zero value, omitnil is the absent value +// of a nil pointer, the alternatives of | pass when one of them passes. func (k typedTags[V]) applyValue(t tagContext, f *shared.Field[V], optional bool, rules []tagRule) error { - for i, r := range rules { - if r.name == "omitempty" { + for _, r := range rules { + switch alts, ok := r.alternatives(); { + case r.name == "omitempty": var zero V f = f.When(func(_ context.Context, v V) bool { return v != zero }) - rules = append(rules[:i:i], rules[i+1:]...) - break + case r.name == "omitnil": + case strings.HasPrefix(r.name, "required_") && t.elem: + return fmt.Errorf("%s isn't supported for the elements", r.name) + case ok: + var err error + configure := make([]func(alt *shared.Field[V]), len(alts)) + for i, alt := range alts { + configure[i] = func(f *shared.Field[V]) { + if e := k.apply(t, f, optional, []tagRule{alt}); e != nil && err == nil { + err = e + } + } + } + f.Or(configure...) + if err != nil { + return err + } + default: + if err := k.apply(t, f, optional, []tagRule{r}); err != nil { + return err + } } } - return k.apply(t, f, optional, rules) + return nil } +var stringKind = typedTags[string]{apply: stringTags, parse: func(s string) (string, error) { return s, nil }} + var kinds = map[reflect.Kind]kindTags{ - reflect.String: typedTags[string]{apply: stringTags}, - reflect.Bool: typedTags[bool]{apply: boolTags}, - reflect.Int: typedTags[int]{apply: numberTags[int]}, - reflect.Int8: typedTags[int8]{apply: numberTags[int8]}, - reflect.Int16: typedTags[int16]{apply: numberTags[int16]}, - reflect.Int32: typedTags[int32]{apply: numberTags[int32]}, - reflect.Int64: typedTags[int64]{apply: numberTags[int64]}, - reflect.Uint: typedTags[uint]{apply: numberTags[uint]}, - reflect.Uint8: typedTags[uint8]{apply: numberTags[uint8]}, - reflect.Uint16: typedTags[uint16]{apply: numberTags[uint16]}, - reflect.Uint32: typedTags[uint32]{apply: numberTags[uint32]}, - reflect.Uint64: typedTags[uint64]{apply: numberTags[uint64]}, - reflect.Float32: typedTags[float32]{apply: numberTags[float32]}, - reflect.Float64: typedTags[float64]{apply: numberTags[float64]}, + reflect.String: stringKind, + reflect.Bool: typedTags[bool]{apply: boolTags, parse: strconv.ParseBool}, + reflect.Int: numberKind[int](), + reflect.Int8: numberKind[int8](), + reflect.Int16: numberKind[int16](), + reflect.Int32: numberKind[int32](), + reflect.Int64: numberKind[int64](), + reflect.Uint: numberKind[uint](), + reflect.Uint8: numberKind[uint8](), + reflect.Uint16: numberKind[uint16](), + reflect.Uint32: numberKind[uint32](), + reflect.Uint64: numberKind[uint64](), + reflect.Float32: numberKind[float32](), + reflect.Float64: numberKind[float64](), +} + +func numberKind[N num.Number]() typedTags[N] { + return typedTags[N]{apply: numberTags[N], parse: parseNumber[N]} } var timeTags = typedTags[time.Time]{apply: timeRules} @@ -358,7 +716,11 @@ var stringRules = map[string]func(c *str.BaseConfigurator) *str.BaseConfigurator "ipv6": (*str.BaseConfigurator).IPv6, "hostname": (*str.BaseConfigurator).Hostname, "hostname_rfc1123": (*str.BaseConfigurator).Hostname, + "alpha": (*str.BaseConfigurator).Alpha, "alphanum": (*str.BaseConfigurator).Alphanumeric, + "number": (*str.BaseConfigurator).Digits, + "numeric": (*str.BaseConfigurator).Numeric, + "hexadecimal": (*str.BaseConfigurator).Hexadecimal, "ascii": (*str.BaseConfigurator).ASCII, "lowercase": (*str.BaseConfigurator).Lowercase, "uppercase": (*str.BaseConfigurator).Uppercase, @@ -376,6 +738,21 @@ var stringRules = map[string]func(c *str.BaseConfigurator) *str.BaseConfigurator "luhn_checksum": (*str.BaseConfigurator).Luhn, } +// stringParamRules are the string rules with a parameter. +var stringParamRules = map[string]func(c *str.BaseConfigurator, param string) *str.BaseConfigurator{ + "eq": func(c *str.BaseConfigurator, v string) *str.BaseConfigurator { return c.AnyOf(v) }, + "startswith": (*str.BaseConfigurator).Prefix, + "endswith": (*str.BaseConfigurator).Suffix, + "contains": (*str.BaseConfigurator).Contains, + "startsnotwith": (*str.BaseConfigurator).NotPrefix, + "endsnotwith": (*str.BaseConfigurator).NotSuffix, + "excludes": (*str.BaseConfigurator).Excludes, + "containsany": (*str.BaseConfigurator).ContainsAny, + "excludesall": (*str.BaseConfigurator).ExcludesAny, + "eq_ignore_case": (*str.BaseConfigurator).EqualFold, + "datetime": (*str.BaseConfigurator).Datetime, +} + func stringTags(t tagContext, f *shared.Field[string], _ bool, rules []tagRule) error { c := str.NewBaseConfigurator(f) for _, r := range rules { @@ -383,36 +760,42 @@ func stringTags(t tagContext, f *shared.Field[string], _ bool, rules []tagRule) rule(c) continue } + if rule, ok := stringParamRules[r.name]; ok { + rule(c, r.param) + continue + } switch r.name { - case "min", "max", "len": + case "min", "max", "len", "gt", "gte", "lt", "lte": n, err := strconv.Atoi(r.param) if err != nil { return fmt.Errorf("%s=%s: %w", r.name, r.param, err) } - if r.name != "max" { + switch r.name { + case "min", "gte": c.MinRunes(n) - } - if r.name != "min" { + case "gt": + c.MinRunes(n + 1) + case "max", "lte": c.MaxRunes(n) + case "lt": + c.MaxRunes(n - 1) + default: + c.MinRunes(n).MaxRunes(n) } case "oneof": c.AnyOf(strings.Fields(r.param)...) - case "eq": - c.AnyOf(r.param) - case "startswith": - c.Prefix(r.param) - case "endswith": - c.Suffix(r.param) - case "contains": - c.Contains(r.param) - case "datetime": - c.Datetime(r.param) - case "eqfield": + case "ne": + eq.NewBaseConfigurator(f, false).NotEqual(r.param) + case "eqfield", "nefield": other, err := otherField[string](t, r) if err != nil { return err } - c.EqualField(other) + if r.name == "eqfield" { + c.EqualField(other) + } else { + c.NotEqualField(other) + } default: return unsupported(r) } @@ -423,10 +806,22 @@ func stringTags(t tagContext, f *shared.Field[string], _ bool, rules []tagRule) func boolTags(_ tagContext, f *shared.Field[bool], optional bool, rules []tagRule) error { c := eq.NewBaseConfigurator(f, optional) for _, r := range rules { - if r.name != "required" { + switch r.name { + case "required": + c.Required() + case "eq", "ne": + b, err := strconv.ParseBool(r.param) + if err != nil { + return fmt.Errorf("%s=%s: %w", r.name, r.param, err) + } + if r.name == "eq" { + c.Equal(b) + } else { + c.NotEqual(b) + } + default: return unsupported(r) } - c.Required() } return nil } @@ -441,7 +836,7 @@ func numberTags[N num.Number](t tagContext, f *shared.Field[N], optional bool, r c.Latitude() case "longitude": c.Longitude() - case "min", "gte", "max", "lte", "eq": + case "min", "gte", "max", "lte", "gt", "lt", "eq", "ne": n, err := parseNumber[N](r.param) if err != nil { return fmt.Errorf("%s=%s: %w", r.name, r.param, err) @@ -451,6 +846,12 @@ func numberTags[N num.Number](t tagContext, f *shared.Field[N], optional bool, r c.Min(n) case "max", "lte": c.Max(n) + case "gt": + c.GreaterThan(n) + case "lt": + c.LessThan(n) + case "ne": + eq.NewBaseConfigurator(f, optional).NotEqual(n) default: c.AnyOf(n) } @@ -464,15 +865,24 @@ func numberTags[N num.Number](t tagContext, f *shared.Field[N], optional bool, r allowed = append(allowed, n) } c.AnyOf(allowed...) - case "gtefield", "ltefield": + case "gtefield", "ltefield", "gtfield", "ltfield", "eqfield", "nefield": other, err := otherField[N](t, r) if err != nil { return err } - if r.name == "gtefield" { + switch r.name { + case "gtefield": c.MinField(other) - } else { + case "ltefield": c.MaxField(other) + case "gtfield": + c.GreaterField(other) + case "ltfield": + c.LessField(other) + case "eqfield": + eq.NewBaseConfigurator(f, optional).EqualField(other) + default: + eq.NewBaseConfigurator(f, optional).NotEqualField(other) } default: return unsupported(r) @@ -502,6 +912,16 @@ func timeRules(t tagContext, f *shared.Field[time.Time], _ bool, rules []tagRule switch r.name { case "required": c.Required() + case "gt", "gte", "lt", "lte": + // without a parameter, the comparison with the current time + if r.param != "" { + return fmt.Errorf("%s=%s: the times are compared with the current time, without a parameter", r.name, r.param) + } + if strings.HasPrefix(r.name, "gt") { + c.InFuture() + } else { + c.InPast() + } case "gtfield", "ltfield": other, err := otherField[time.Time](t, r) if err != nil { @@ -519,13 +939,10 @@ func timeRules(t tagContext, f *shared.Field[time.Time], _ bool, rules []tagRule return nil } -// otherField returns the pointer to the field of the model named by the parameter of the rule, a sibling field -// of the field of the tag or its nested field, Inner.Field. Its type must be V or a named type of V. -func otherField[V any](t tagContext, r tagRule) (*V, error) { - if t.elem { - return nil, fmt.Errorf("%s isn't supported for the elements", r.name) - } - path := r.param +// other returns the field of the model by the name of the parameter of the rule: a sibling field of the field +// of the tag or its nested field, Inner.Field. +func (t tagContext) other(r tagRule, name string) (fmap.Field, error) { + path := name if parent := t.field.GetParent(); parent != nil { path = parent.GetStructPath() + "." + path } @@ -533,9 +950,22 @@ func otherField[V any](t tagContext, r tagRule) (*V, error) { if !ok { return nil, fmt.Errorf("%s=%s: no field %s", r.name, r.param, path) } + return other, nil +} + +// otherField returns the pointer to the field of the model named by the parameter of the rule, see other. +// Its type must be V or a named type of V. +func otherField[V any](t tagContext, r tagRule) (*V, error) { + if t.elem { + return nil, fmt.Errorf("%s isn't supported for the elements", r.name) + } + other, err := t.other(r, r.param) + if err != nil { + return nil, err + } want := reflect.TypeFor[V]() if typ := other.GetType(); typ.Kind() != want.Kind() || typ.Size() != want.Size() { - return nil, fmt.Errorf("%s=%s: the field %s has type %s, %s expected", r.name, r.param, path, typ, want) + return nil, fmt.Errorf("%s=%s: the field %s has type %s, %s expected", r.name, r.param, other.GetStructPath(), typ, want) } return (*V)(reflect.ValueOf(other.GetPtr(t.model)).UnsafePointer()), nil } diff --git a/internal/tags/tags_test.go b/internal/tags/tags_test.go index c86b592..6910eee 100644 --- a/internal/tags/tags_test.go +++ b/internal/tags/tags_test.go @@ -183,9 +183,6 @@ func TestTagsErrors(t *testing.T) { {"unknown rule", tagsOf[struct { A string `validate:"required,isbn"` }], `valigo: tag validate:"required,isbn" of field A: the rule isbn isn't supported for the field, use the rules in code`}, - {"alternatives", tagsOf[struct { - A string `validate:"email|url"` - }], `valigo: tag validate:"email|url" of field A: the alternatives of | aren't supported, use When or Custom`}, {"bad number", tagsOf[struct { A int `validate:"min=x"` }], `valigo: tag validate:"min=x" of field A: min=x: strconv.ParseInt: parsing "x": invalid syntax`}, @@ -210,9 +207,6 @@ func TestTagsErrors(t *testing.T) { {"unique of pointers", tagsOf[struct { A []*string `validate:"unique"` }], `valigo: tag validate:"unique" of field A: unique of the slices of pointers isn't supported`}, - {"dive into structs", tagsOf[struct { - A []tagsAddress `validate:"dive"` - }], `valigo: tag validate:"dive" of field A: the elements of type tags_test.tagsAddress aren't supported, configure the rules of their type`}, {"dive into a map of ints", tagsOf[struct { A map[int]string `validate:"dive,required"` }], `valigo: tag validate:"dive,required" of field A: dive is supported for the maps of strings to values, map[string]V`}, From 96e1b78dd9dd1f657072b74374e49f83c116d825 Mon Sep 17 00:00:00 2001 From: Dmitri Aleksandrov Date: Mon, 19 Oct 2026 12:30:30 +0300 Subject: [PATCH 3/3] docs: list all tags of go-playground/validator: supported, different and in code --- docs/features/tags.md | 62 ++++++++++++++++++++++++++++++++---------- skills/valigo/SKILL.md | 2 +- 2 files changed, 48 insertions(+), 16 deletions(-) diff --git a/docs/features/tags.md b/docs/features/tags.md index 94f5935..9809535 100644 --- a/docs/features/tags.md +++ b/docs/features/tags.md @@ -61,23 +61,55 @@ Nick - Should contain only letters and digits - string.alphanumeric ## Rules -| Fields | Rules | +| Fields | Tags of go-playground/validator | Rules of valigo | +|---|---|---| +| all | `required` | `Required`: a string is not empty, a number is not zero, a bool is `true`, a slice and a map have elements, a pointer is not nil | +| all | `omitempty`, `omitnil` | the next rules are skipped for the zero value; a nil pointer is absent anyway | +| all | `required_if=F v`, `required_unless=F v`, `required_with=F G`, `required_with_all`, `required_without`, `required_without_all` | `Required` under the condition of the fields `F`, `G` of the same struct: their values, or their values are not zero | +| all | `a\|b` | `Or`: one of the alternatives passes, the errors of the first one when none does | +| strings | `min`, `max`, `len`, `gt`, `gte`, `lt`, `lte` | `MinRunes`, `MaxRunes`: the lengths in characters | +| strings | `eq`, `ne`, `oneof=a b`, `eq_ignore_case` | `AnyOf`, `eq.NotEqual`, `AnyOf`, `EqualFold` | +| strings | `contains`, `excludes`, `startswith`, `endswith`, `startsnotwith`, `endsnotwith`, `containsany`, `excludesall` | `Contains`, `Excludes`, `Prefix`, `Suffix`, `NotPrefix`, `NotSuffix`, `ContainsAny`, `ExcludesAny` | +| strings | `alpha`, `alphanum`, `number`, `numeric`, `hexadecimal`, `ascii`, `lowercase`, `uppercase` | `Alpha`, `Alphanumeric`, `Digits`, `Numeric`, `Hexadecimal`, `ASCII`, `Lowercase`, `Uppercase` | +| strings | `email`, `url`, `http_url`, `uuid`, `ip`, `ipv4`, `ipv6`, `cidr`, `mac`, `hostname`, `hostname_rfc1123`, `e164` | `Email`, `URL`, `URL`, `UUID`, `IP`, `IPv4`, `IPv6`, `CIDR`, `MAC`, `Hostname`, `Hostname`, `E164` | +| strings | `base64`, `base64url`, `json`, `semver`, `hexcolor`, `datetime=2006-01-02`, `iso3166_1_alpha2`, `iso4217`, `credit_card`, `luhn_checksum` | `Base64`, `Base64URL`, `JSON`, `Semver`, `HexColor`, `Datetime`, `CountryCode`, `CurrencyCode`, `CreditCard`, `Luhn` | +| strings | `eqfield`, `nefield` | `EqualField`, `NotEqualField` | +| numbers | `min`, `gte`, `max`, `lte`, `gt`, `lt`, `eq`, `ne`, `oneof=1 2` | `Min`, `Max`, `GreaterThan`, `LessThan`, `AnyOf`, `eq.NotEqual`, `AnyOf` | +| numbers | `gtefield`, `ltefield`, `gtfield`, `ltfield`, `eqfield`, `nefield` | `MinField`, `MaxField`, `GreaterField`, `LessField`, `eq.EqualField`, `eq.NotEqualField` | +| numbers | `latitude`, `longitude` | `Latitude`, `Longitude` | +| `bool` | `eq=true`, `ne=true` | `eq.Equal`, `eq.NotEqual` | +| `time.Time` | `gt`, `gte`, `lt`, `lte` without a parameter, `gtfield`, `ltfield` | `InFuture`, `InPast`, `AfterField`, `BeforeField` | +| slices, maps | `min`, `max`, `len`, `gt`, `gte`, `lt`, `lte`, `eq` | the rules of the length | +| slices | `unique` | `eq.Slice(...).Unique()` of the elements of comparable types | +| slices | `dive` | the next rules are the rules of the elements; the elements of struct types are validated by the tags of their type, `Items[1].Title`, `dive,required` checks nil elements of `[]*T` | +| maps | `dive`, `dive,keys,...,endkeys,...` | the rules of the values and of the keys of `map[string]V` | +| pointers to nested structs | `required` | the fields of a nested struct have their own tags | + +Pointers to the values have the rules of the values, a nil pointer is absent. The rules on fields and the conditions take the names of the fields of the same struct, or their nested fields `Inner.Field`. `0x2C` in a parameter is a comma, `0x7C` is a pipe, like in go-playground/validator. + +## Not supported + +These tags panic in `Configure`: a typo or an unsupported rule doesn't turn into a missing check. Write their rules in code. + +| Tags | In code | |---|---| -| all | `required`, `omitempty` — the next rules are skipped for the zero value | -| strings | `min`, `max`, `len` in characters, `eq`, `oneof=a b`, `startswith`, `endswith`, `contains`, `email`, `url`, `http_url`, `uuid`, `ip`, `ipv4`, `ipv6`, `hostname`, `hostname_rfc1123`, `alphanum`, `ascii`, `lowercase`, `uppercase`, `e164`, `base64`, `base64url`, `json`, `semver`, `cidr`, `mac`, `hexcolor`, `iso3166_1_alpha2`, `iso4217`, `credit_card`, `luhn_checksum`, `datetime=2006-01-02`, `eqfield` | -| numbers | `min`, `gte`, `max`, `lte`, `eq`, `oneof=1 2`, `latitude`, `longitude`, `gtefield`, `ltefield` | -| `bool` | `required`: `true` | -| `time.Time` | `required`, `gtfield`, `ltfield` | -| slices | `required`, `min`, `max`, `len` of the length, `unique`, `dive` — the next rules are the rules of the elements | -| maps | `required`, `min`, `max`, `len` of the length, `dive` — the next rules are the rules of the values of `map[string]V` | -| pointers to nested structs | `required`; the fields have their own tags | - -Pointers to the values have the rules of the values, a nil pointer is absent. `eqfield`, `gtefield` and the other rules on fields take the name of a field of the same struct, or its nested field `Inner.Field`. +| `excluded_if`, `excluded_unless`, `excluded_with`, `excluded_with_all`, `excluded_without`, `excluded_without_all` | `b.When(cond).Field(&m.X).Custom(...)` that fails on a present value | +| `eqcsfield`, `necsfield`, `gtcsfield`, `gtecsfield`, `ltcsfield`, `ltecsfield`, `fieldcontains`, `fieldexcludes` | the rules on other fields with the pointers to any field of the model, `EqualField(&m.Other.Field)`, or `b.Custom` | +| `alphaunicode`, `alphanumunicode`, `boolean`, `containsrune`, `excludesrune`, `multibyte`, `printascii`, `ne_ignore_case`, `oneofci` | `Custom` or `Regexp` | +| `uuid3`, `uuid4`, `uuid5`, `uuid_rfc4122`... , `ulid`, `cve` | `UUID` with `Custom` of the version, `Regexp` | +| `uri`, `urn_rfc2141`, `url_encoded`, `datauri`, `fqdn`, `hostname_port`, `tcp_addr`, `udp_addr`, `unix_addr`, `ip_addr`... , `cidrv4`, `cidrv6` | `URL`, `Hostname`, `IP`, `CIDR` with `Custom`, or `Custom` with the parsers of the standard library | +| `isbn`, `issn`, `bic`, `ssn`, `jwt`, `html`, `html_encoded`, `rgb`, `rgba`, `hsl`, `hsla`, `iscolor`, `md5`, `sha256`..., `btc_addr`, `eth_addr`, `mongodb`, `cron`, `timezone`, `bcp47_language_tag`, `iso3166_1_alpha3`, `iso3166_1_alpha_numeric`, `iso3166_2`, `iso4217_numeric`, `postcode_iso3166_alpha2` | `Custom` or `Regexp` | +| `dir`, `dirpath`, `file`, `filepath`, `image` | `Custom`: valigo doesn't touch the file system | +| `isdefault`, `omitzero`, `structonly`, `nostructlevel`, `skip_unless` | `When` and `Custom` | +| `dive` into the elements of slices of slices, of maps with other keys than strings, of maps of pointers and structs; `unique` of the slices of pointers and structs, `unique=Field` | `Each`, `EachKey`, `EachValue` and `Custom` in code | +| the custom tags of `RegisterValidation`, the aliases of `RegisterAlias` | the rules of the type in code, see [Your types](conversions.md#your-types) | ## Differences from go-playground/validator -- `required` is `Required` of valigo: a string is not empty, a number is not zero, a slice and a map have elements — go-playground/validator accepts an empty non-nil slice. +- `required` is `Required` of valigo: a string is not empty, a number is not zero, a slice and a map have elements — go-playground/validator accepts an empty non-nil slice and map, and a pointer to an empty string. - The fields of a nil nested struct are skipped, like by go-playground/validator. The rules in code check `Required` of these fields, see [Absent values](absent.md). -- `dive` into the elements of structs, `keys`/`endkeys`, the alternatives `|`, `gt`/`lt` of numbers and the custom tags of go-playground/validator aren't supported: write these rules in code, with `When` and `Custom`. -- An unknown rule panics in `Configure`, like an invalid rule in code, so a typo doesn't turn into a missing check. -- The rules after `omitempty` aren't in the JSON Schema: they don't apply to every value. +- The messages are the messages of valigo in the languages of the users, the errors have the [codes](errors.md#codes-for-clients) of valigo; the alternatives `a|b` report the errors of the first one. +- The formats are the formats of valigo, see [Strings](strings.md): `email`, `url` and `hostname` can differ from go-playground/validator in details. +- `gt`, `lt` of `time.Time` compare with the current time without a parameter, like go-playground/validator, and fail on a parameter. +- The rules of the tags after `omitempty` and the conditional ones aren't in the [JSON Schema](schema.md): they don't apply to every value. +- A valid object is validated without allocations, also with `dive` into the elements of structs; the alternatives allocate the errors of the failed ones. diff --git a/skills/valigo/SKILL.md b/skills/valigo/SKILL.md index 938d36a..e4cf48f 100644 --- a/skills/valigo/SKILL.md +++ b/skills/valigo/SKILL.md @@ -180,7 +180,7 @@ func main() { ## Rules from tags -`b.Tags("validate")` in `Configure` applies go-playground/validator tags (`required`, `min`/`max`/`len`, `oneof`, `email`, `url`, `uuid`, `gte`/`lte`, `eqfield`, `gtefield`, `dive`, `unique`, `omitempty`...) as valigo rules, mixable with code rules. Unknown rules, `|`, `keys`, dive into structs panic in Configure: write them in code. Fields of nil nested structs are skipped (unlike code rules). +`b.Tags("validate")` in `Configure` applies go-playground/validator tags as valigo rules, mixable with code rules: `required`, `omitempty`, `required_if`/`required_with`/`required_without`..., `a|b`, lengths and comparisons (`min`, `max`, `len`, `gt`, `lt`, `eq`, `ne`, `oneof`), the formats, the rules on fields (`eqfield`, `gtfield`...), `dive` into elements (structs too, by their tags), `keys`/`endkeys` of `map[string]V`, `unique`. Unsupported tags (`excluded_*`, `*csfield`, `uuid4`, `isbn`..., custom tags) panic in Configure: write them in code. Fields of nil nested structs are skipped (unlike code rules). ## JSON Schema