From cd9cda823e3e96f3b8c08d801f31cfaf8c4c0c58 Mon Sep 17 00:00:00 2001 From: Dmitri Aleksandrov Date: Mon, 19 Oct 2026 11:42:37 +0300 Subject: [PATCH 1/4] test(timex): test the package from outside The tests import valigo, and valigo is going to import timex for the rules of tags: an internal test package would be an import cycle. SetNow of export_test.go replaces the current time. --- timex/base_test.go | 83 ++++++++++++++++++++++---------------------- timex/export_test.go | 12 +++++++ 2 files changed, 53 insertions(+), 42 deletions(-) create mode 100644 timex/export_test.go diff --git a/timex/base_test.go b/timex/base_test.go index 63a4919..6edcdc0 100644 --- a/timex/base_test.go +++ b/timex/base_test.go @@ -1,4 +1,4 @@ -package timex +package timex_test import ( "context" @@ -10,6 +10,7 @@ import ( "github.com/insei/valigo" "github.com/insei/valigo/internal/testenv" "github.com/insei/valigo/shared" + "github.com/insei/valigo/timex" ) type event struct { @@ -38,8 +39,7 @@ func validate(t *testing.T, cfg func(c valigo.Configurator[event], m *event), ob } func TestRules(t *testing.T) { - now = func() time.Time { return day2 } - t.Cleanup(func() { now = time.Now }) + timex.SetNow(t, func() time.Time { return day2 }) tests := []struct { name string @@ -47,35 +47,35 @@ func TestRules(t *testing.T) { obj *event want []string }{ - {"required zero", func(c valigo.Configurator[event], m *event) { c.Field(&m.At).As(Of).Required() }, &event{}, []string{"At: Should be fulfilled"}}, - {"required nil", func(c valigo.Configurator[event], m *event) { c.Field(&m.AtPtr).As(Of).Required() }, &event{}, []string{"AtPtr: Should be fulfilled"}}, - {"required ok", func(c valigo.Configurator[event], m *event) { c.Field(&m.AtPtr).As(Of).Required() }, &event{AtPtr: &day1}, nil}, - {"before", func(c valigo.Configurator[event], m *event) { c.Field(&m.At).As(Of).Before(day2) }, &event{At: day2}, []string{"At: Should be before 2026-01-02T00:00:00Z"}}, - {"before ok", func(c valigo.Configurator[event], m *event) { c.Field(&m.At).As(Of).Before(day2) }, &event{At: day1}, nil}, - {"after", func(c valigo.Configurator[event], m *event) { c.Field(&m.At).As(Of).After(day2) }, &event{At: day2}, []string{"At: Should be after 2026-01-02T00:00:00Z"}}, - {"after ok", func(c valigo.Configurator[event], m *event) { c.Field(&m.At).As(Of).After(day2) }, &event{At: day3}, nil}, + {"required zero", func(c valigo.Configurator[event], m *event) { c.Field(&m.At).As(timex.Of).Required() }, &event{}, []string{"At: Should be fulfilled"}}, + {"required nil", func(c valigo.Configurator[event], m *event) { c.Field(&m.AtPtr).As(timex.Of).Required() }, &event{}, []string{"AtPtr: Should be fulfilled"}}, + {"required ok", func(c valigo.Configurator[event], m *event) { c.Field(&m.AtPtr).As(timex.Of).Required() }, &event{AtPtr: &day1}, nil}, + {"before", func(c valigo.Configurator[event], m *event) { c.Field(&m.At).As(timex.Of).Before(day2) }, &event{At: day2}, []string{"At: Should be before 2026-01-02T00:00:00Z"}}, + {"before ok", func(c valigo.Configurator[event], m *event) { c.Field(&m.At).As(timex.Of).Before(day2) }, &event{At: day1}, nil}, + {"after", func(c valigo.Configurator[event], m *event) { c.Field(&m.At).As(timex.Of).After(day2) }, &event{At: day2}, []string{"At: Should be after 2026-01-02T00:00:00Z"}}, + {"after ok", func(c valigo.Configurator[event], m *event) { c.Field(&m.At).As(timex.Of).After(day2) }, &event{At: day3}, nil}, {"between bounds", func(c valigo.Configurator[event], m *event) { - c.Field(&m.At).As(Of).Between(day1, day2) - c.Field(&m.AtPtr).As(Of).Between(day1, day2) + c.Field(&m.At).As(timex.Of).Between(day1, day2) + c.Field(&m.AtPtr).As(timex.Of).Between(day1, day2) }, &event{At: day1, AtPtr: &day2}, nil}, - {"between outside", func(c valigo.Configurator[event], m *event) { c.Field(&m.At).As(Of).Between(day1, day2) }, &event{At: day3}, + {"between outside", func(c valigo.Configurator[event], m *event) { c.Field(&m.At).As(timex.Of).Between(day1, day2) }, &event{At: day3}, []string{"At: Should be between 2026-01-01T00:00:00Z and 2026-01-02T00:00:00Z"}}, - {"in past", func(c valigo.Configurator[event], m *event) { c.Field(&m.At).As(Of).InPast() }, &event{At: day3}, []string{"At: Should be in the past"}}, - {"in past ok", func(c valigo.Configurator[event], m *event) { c.Field(&m.At).As(Of).InPast() }, &event{At: day1}, nil}, - {"in future", func(c valigo.Configurator[event], m *event) { c.Field(&m.At).As(Of).InFuture() }, &event{At: day1}, []string{"At: Should be in the future"}}, - {"in future ok", func(c valigo.Configurator[event], m *event) { c.Field(&m.At).As(Of).InFuture() }, &event{At: day3}, nil}, - {"before field", func(c valigo.Configurator[event], m *event) { c.Field(&m.At).As(Of).BeforeField(&m.Start) }, &event{At: day2, Start: day1}, []string{"At: Should be before Start"}}, - {"before field ok", func(c valigo.Configurator[event], m *event) { c.Field(&m.At).As(Of).BeforeField(&m.Start) }, &event{At: day1, Start: day2}, nil}, - {"after field", func(c valigo.Configurator[event], m *event) { c.Field(&m.AtPtr).As(Of).AfterField(&m.Start) }, &event{AtPtr: &day1, Start: day2}, []string{"AtPtr: Should be after Start"}}, - {"after field ok", func(c valigo.Configurator[event], m *event) { c.Field(&m.AtPtr).As(Of).AfterField(&m.Start) }, &event{AtPtr: &day3, Start: day2}, nil}, + {"in past", func(c valigo.Configurator[event], m *event) { c.Field(&m.At).As(timex.Of).InPast() }, &event{At: day3}, []string{"At: Should be in the past"}}, + {"in past ok", func(c valigo.Configurator[event], m *event) { c.Field(&m.At).As(timex.Of).InPast() }, &event{At: day1}, nil}, + {"in future", func(c valigo.Configurator[event], m *event) { c.Field(&m.At).As(timex.Of).InFuture() }, &event{At: day1}, []string{"At: Should be in the future"}}, + {"in future ok", func(c valigo.Configurator[event], m *event) { c.Field(&m.At).As(timex.Of).InFuture() }, &event{At: day3}, nil}, + {"before field", func(c valigo.Configurator[event], m *event) { c.Field(&m.At).As(timex.Of).BeforeField(&m.Start) }, &event{At: day2, Start: day1}, []string{"At: Should be before Start"}}, + {"before field ok", func(c valigo.Configurator[event], m *event) { c.Field(&m.At).As(timex.Of).BeforeField(&m.Start) }, &event{At: day1, Start: day2}, nil}, + {"after field", func(c valigo.Configurator[event], m *event) { c.Field(&m.AtPtr).As(timex.Of).AfterField(&m.Start) }, &event{AtPtr: &day1, Start: day2}, []string{"AtPtr: Should be after Start"}}, + {"after field ok", func(c valigo.Configurator[event], m *event) { c.Field(&m.AtPtr).As(timex.Of).AfterField(&m.Start) }, &event{AtPtr: &day3, Start: day2}, nil}, {"nil skipped", func(c valigo.Configurator[event], m *event) { - c.Field(&m.AtPtr).As(Of).Before(day1).After(day3).InPast().InFuture() + c.Field(&m.AtPtr).As(timex.Of).Before(day1).After(day3).InPast().InFuture() }, &event{}, nil}, {"when", func(c valigo.Configurator[event], m *event) { - c.Field(&m.At).As(Of).When(func(_ context.Context, v time.Time) bool { return !v.IsZero() }).After(day2) + c.Field(&m.At).As(timex.Of).When(func(_ context.Context, v time.Time) bool { return !v.IsZero() }).After(day2) }, &event{}, nil}, {"custom", func(c valigo.Configurator[event], m *event) { - c.Field(&m.At).As(Of).Custom(func(ctx context.Context, h *shared.FieldCustomHelper, v time.Time) []shared.Error { + c.Field(&m.At).As(timex.Of).Custom(func(ctx context.Context, h *shared.FieldCustomHelper, v time.Time) []shared.Error { if v.Weekday() == time.Thursday { return []shared.Error{h.ErrorT(ctx, v, "Not on Thursdays")} } @@ -83,13 +83,13 @@ func TestRules(t *testing.T) { }) }, &event{At: day1}, []string{"At: Not on Thursdays"}}, {"slice", func(c valigo.Configurator[event], m *event) { - c.Slice(&m.Dates).As(Slice).MaxLen(2).Each(func(e *BaseConfigurator) { e.After(day1) }) + c.Slice(&m.Dates).As(timex.Slice).MaxLen(2).Each(func(e *timex.BaseConfigurator) { e.After(day1) }) }, &event{Dates: []time.Time{day2, day1, day3}}, []string{ "Dates: Cannot contain more than 2 elements", "Dates[1]: Should be after 2026-01-01T00:00:00Z", }}, {"slice of pointers", func(c valigo.Configurator[event], m *event) { - c.Slice(&m.Breaks).As(Slice).Each(func(e *BaseConfigurator) { e.Required() }) + c.Slice(&m.Breaks).As(timex.Slice).Each(func(e *timex.BaseConfigurator) { e.Required() }) }, &event{Breaks: []*time.Time{&day1, nil}}, []string{"Breaks[1]: Should be fulfilled"}}, } for _, tt := range tests { @@ -101,7 +101,7 @@ func TestRules(t *testing.T) { func TestErrorValue(t *testing.T) { v := valigo.New() - valigo.Configure[event](v, func(c valigo.Configurator[event], m *event) { c.Field(&m.At).As(Of).After(day2) }) + valigo.Configure[event](v, func(c valigo.Configurator[event], m *event) { c.Field(&m.At).As(timex.Of).After(day2) }) errs := v.ValidateTyped(context.Background(), &event{At: day1}) assert.Equal(t, []shared.Error{{Location: "At", Message: "Should be after 2026-01-02T00:00:00Z", Value: day1, Code: "time.after", Params: map[string]any{"time": "2026-01-02T00:00:00Z"}}}, errs) } @@ -112,9 +112,9 @@ func TestZeroAllocationsOnValid(t *testing.T) { } v := valigo.New() valigo.Configure[event](v, func(c valigo.Configurator[event], m *event) { - c.Field(&m.At).As(Of).Required().Between(day1, day3).InPast() - c.Field(&m.AtPtr).As(Of).Before(day3) - c.Slice(&m.Dates).As(Slice).Each(func(e *BaseConfigurator) { e.After(day1) }) + c.Field(&m.At).As(timex.Of).Required().Between(day1, day3).InPast() + c.Field(&m.AtPtr).As(timex.Of).Before(day3) + c.Slice(&m.Dates).As(timex.Slice).Each(func(e *timex.BaseConfigurator) { e.After(day1) }) }) obj := &event{At: day2, AtPtr: &day1, Dates: []time.Time{day2}} ctx := context.Background() @@ -123,25 +123,24 @@ func TestZeroAllocationsOnValid(t *testing.T) { } func TestCodes(t *testing.T) { - now = func() time.Time { return day2 } - t.Cleanup(func() { now = time.Now }) + timex.SetNow(t, func() time.Time { return day2 }) tests := []struct { code string - cfg func(c *BaseConfigurator, m *event) + cfg func(c *timex.BaseConfigurator, m *event) obj *event }{ - {"time.required", func(c *BaseConfigurator, m *event) { c.Required() }, &event{}}, - {"time.before", func(c *BaseConfigurator, m *event) { c.Before(day1) }, &event{At: day2}}, - {"time.after", func(c *BaseConfigurator, m *event) { c.After(day3) }, &event{At: day2}}, - {"time.between", func(c *BaseConfigurator, m *event) { c.Between(day3, day3) }, &event{At: day2}}, - {"time.before_field", func(c *BaseConfigurator, m *event) { c.BeforeField(&m.Start) }, &event{At: day2, Start: day1}}, - {"time.after_field", func(c *BaseConfigurator, m *event) { c.AfterField(&m.Start) }, &event{At: day1, Start: day2}}, - {"time.in_past", func(c *BaseConfigurator, m *event) { c.InPast() }, &event{At: day3}}, - {"time.in_future", func(c *BaseConfigurator, m *event) { c.InFuture() }, &event{At: day1}}, + {"time.required", func(c *timex.BaseConfigurator, m *event) { c.Required() }, &event{}}, + {"time.before", func(c *timex.BaseConfigurator, m *event) { c.Before(day1) }, &event{At: day2}}, + {"time.after", func(c *timex.BaseConfigurator, m *event) { c.After(day3) }, &event{At: day2}}, + {"time.between", func(c *timex.BaseConfigurator, m *event) { c.Between(day3, day3) }, &event{At: day2}}, + {"time.before_field", func(c *timex.BaseConfigurator, m *event) { c.BeforeField(&m.Start) }, &event{At: day2, Start: day1}}, + {"time.after_field", func(c *timex.BaseConfigurator, m *event) { c.AfterField(&m.Start) }, &event{At: day1, Start: day2}}, + {"time.in_past", func(c *timex.BaseConfigurator, m *event) { c.InPast() }, &event{At: day3}}, + {"time.in_future", func(c *timex.BaseConfigurator, m *event) { c.InFuture() }, &event{At: day1}}, } for _, tt := range tests { v := valigo.New() - valigo.Configure[event](v, func(c valigo.Configurator[event], m *event) { tt.cfg(c.Field(&m.At).As(Of), m) }) + valigo.Configure[event](v, func(c valigo.Configurator[event], m *event) { tt.cfg(c.Field(&m.At).As(timex.Of), m) }) errs := v.ValidateTyped(context.Background(), tt.obj) if assert.Len(t, errs, 1, tt.code) { assert.Equal(t, tt.code, errs[0].Code) diff --git a/timex/export_test.go b/timex/export_test.go new file mode 100644 index 0000000..bae00b7 --- /dev/null +++ b/timex/export_test.go @@ -0,0 +1,12 @@ +package timex + +import ( + "testing" + "time" +) + +// SetNow replaces the current time of InPast and InFuture for the test. +func SetNow(t testing.TB, fn func() time.Time) { + now = fn + t.Cleanup(func() { now = time.Now }) +} From bf5a86795b5e22c714925b497b0e58f722ecfe64 Mon Sep 17 00:00:00 2001 From: Dmitri Aleksandrov Date: Mon, 19 Oct 2026 11:42:37 +0300 Subject: [PATCH 2/4] feat: configure the rules of the tags of go-playground/validator Configurator.Tags("validate") configures the rules of the tags of the fields of the struct and of its nested structs, validate:"required,max=64", by the rules of valigo with their messages, codes and constraints: the rules of strings, numbers, bools, times, the lengths of slices and maps, dive into the elements and the values of map[string]V, unique, the rules on other fields, omitempty. The rules of the fields of a nil nested struct are skipped, like by go-playground/validator. An unknown rule panics in Configure. shared.InStruct reports whether the nested structs of a field are present. --- shared/field.go | 9 + shared/field_test.go | 7 + tags.go | 537 +++++++++++++++++++++++++++++++++++++++++++ tags_test.go | 275 ++++++++++++++++++++++ 4 files changed, 828 insertions(+) create mode 100644 tags.go create mode 100644 tags_test.go diff --git a/shared/field.go b/shared/field.go index 68fa95a..29bcf9b 100644 --- a/shared/field.go +++ b/shared/field.go @@ -211,6 +211,15 @@ func valueGetter[T any](field fmap.Field) func(obj any) *T { } } +// InStruct returns a function that reports whether the nested structs stored by pointer, which the field is in, +// are allocated in obj, a pointer to the configured struct: false for the fields of a nil nested struct. +func InStruct(field fmap.Field) func(obj any) bool { + addr := fieldAddr(field) + return func(obj any) bool { + return addr(dataPtr(obj)) != nil + } +} + // fieldAddr returns a function that computes the address of the field in the struct at root by the offsets of fmap, // without reflect: the offset of a field is from the root struct or from the struct of its nearest ancestor stored // by pointer, so the address follows the pointers of these ancestors. It returns nil if one of them is nil. diff --git a/shared/field_test.go b/shared/field_test.go index 4aa1ea8..b8d04df 100644 --- a/shared/field_test.go +++ b/shared/field_test.go @@ -315,3 +315,10 @@ func TestCheckWithForeignPointerPanics(t *testing.T) { NewValueField[string](sampleField(t, "Text"), pathHelper{}, sampleFields, r.add, nil).CheckWith(&foreign, func(string, string) bool { return true }, "bad") }) } + +func TestInStruct(t *testing.T) { + present := InStruct(sampleField(t, "Inner.Text")) + assert.True(t, present(&sample{Inner: &inner{}})) + assert.False(t, present(&sample{})) + assert.True(t, InStruct(sampleField(t, "Text"))(&sample{})) +} diff --git a/tags.go b/tags.go new file mode 100644 index 0000000..37e605b --- /dev/null +++ b/tags.go @@ -0,0 +1,537 @@ +package valigo + +import ( + "context" + "errors" + "fmt" + "reflect" + "strconv" + "strings" + "time" + + "github.com/insei/fmap/v3" + + "github.com/insei/valigo/eq" + "github.com/insei/valigo/num" + "github.com/insei/valigo/shared" + "github.com/insei/valigo/str" + "github.com/insei/valigo/timex" +) + +// Tags configures the rules of the tag name of the fields of T and of its nested structs in the syntax of +// go-playground/validator, validate:"required,max=64", for a migration from it: the tags and the rules in code +// can be mixed in one Configure. The rules are the rules of valigo with their messages, codes and constraints: +// required is Required, min and max are the lengths in characters of strings, the values of numbers and the lengths +// of slices and maps, dive applies the next rules to the elements of a slice or the values of a map[string]V. +// The rules of the fields of a nil nested struct are skipped, like by go-playground/validator, unlike the rules in code. +// See the documentation for the list of the rules. Tags panics on an unknown rule, like Configure on invalid rules. +func (c Configurator[T]) Tags(name string) { + for _, path := range c.b.fields.GetAllPaths() { + field := c.b.fields.MustFind(path) + tag := field.GetTag().Get(name) + if tag == "" || tag == "-" { + continue + } + t := tagContext{field: field, h: c.b.v.helper, fields: c.field, add: inStruct(field, c.add), describe: c.describe(), + storage: c.b.fields, model: c.b.obj} + if err := t.apply(parseTag(tag)); err != nil { + panic(fmt.Sprintf("valigo: tag %s:%q of field %s: %v", name, tag, path, err)) + } + } +} + +// 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) { + nested := false + for parent := field.GetParent(); parent != nil; parent = parent.GetParent() { + nested = nested || parent.GetType().Kind() == reflect.Pointer + } + if !nested { + return add + } + present := shared.InStruct(field) + return func(fn shared.ValidationFn) { + add(func(ctx context.Context, h shared.Helper, obj any, errs []shared.Error) []shared.Error { + if !present(obj) { + return errs + } + return fn(ctx, h, obj, errs) + }) + } +} + +// tagRule is a rule of a tag: name=param. +type tagRule struct { + name, param string +} + +func parseTag(tag string) []tagRule { + parts := strings.Split(tag, ",") + rules := make([]tagRule, len(parts)) + for i, part := range parts { + name, param, _ := strings.Cut(part, "=") + rules[i] = tagRule{name: name, param: param} + } + return rules +} + +// tagContext is the field of the tag with the arguments of the configurators. +type tagContext struct { + field fmap.Field + h shared.Helper + fields shared.Fields + add func(fn shared.ValidationFn) + describe shared.Describe + storage fmap.Storage + model any + // elem is true for the rules of the elements after dive + elem bool +} + +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") + } + } + typ := t.field.GetType() + ptr := typ.Kind() == reflect.Pointer + if ptr { + typ = typ.Elem() + } + switch { + case typ.Kind() == reflect.Slice || typ.Kind() == reflect.Map: + return t.container(typ, ptr, rules) + case typ == timeType: + return timeTags.value(t, ptr, rules) + case typ.Kind() == reflect.Struct: + return t.structRules(ptr, rules) + } + kind, ok := kinds[typ.Kind()] + if !ok { + return fmt.Errorf("the fields of type %s aren't supported", t.field.GetType()) + } + return kind.value(t, ptr, rules) +} + +// 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 == "required" && ptr: + f := shared.NewValueField[*struct{}](t.field, t.h, t.fields, t.add, t.describe) + f.Schema(shared.KeywordRequired, true) + f.RequiredMsg(func(p *struct{}) bool { return p != nil }, shared.M("value.required", valueRequiredKey)) + default: + return unsupported(r) + } + } + return nil +} + +const ( + valueRequiredKey = "validation:value:Should be fulfilled" + sliceRequiredKey = "validation:slice:Should be fulfilled" + sliceMaxLenKey = "validation:slice:Cannot contain more than %d elements" + sliceMinLenKey = "validation:slice:Cannot contain less than %d elements" + mapRequiredKey = "validation:map:Should be fulfilled" + mapMaxLenKey = "validation:map:Cannot contain more than %d elements" + 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. +func (t tagContext) container(typ reflect.Type, ptr bool, rules []tagRule) error { + own, elems := rules, []tagRule(nil) + for i, r := range rules { + if r.name == "dive" { + own, elems = rules[:i], rules[i+1:] + break + } + } + isMap := typ.Kind() == reflect.Map + if err := t.lenRules(isMap, ptr, own); err != nil { + return err + } + unique := false + for _, r := range own { + unique = unique || r.name == "unique" + } + if elems == nil && !unique { + return nil + } + elem := typ.Elem() + elemPtr := elem.Kind() == reflect.Pointer + if elemPtr { + elem = elem.Elem() + } + kind, ok := kinds[elem.Kind()] + if elem == timeType { + kind, ok = timeTags, true + } + switch { + case !ok: + return fmt.Errorf("the elements of type %s aren't supported, configure the rules of their type", typ.Elem()) + 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) + case unique && elemPtr: + return errors.New("unique of the slices of pointers isn't supported") + case unique: + kind.unique(t) + } + if elems == nil { + return nil + } + return kind.elems(t, elemPtr, elems) +} + +// 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; + // the values of these types never get to the errors, only the lengths + if isMap { + return lengthRules(t, ptr, rules, func(m map[struct{}]struct{}) int { return len(m) }, lengthMsgs{ + code: "map", required: mapRequiredKey, minKey: mapMinLenKey, maxKey: mapMaxLenKey, + minWord: "minProperties", maxWord: "maxProperties", + }) + } + return lengthRules(t, ptr, rules, func(s []struct{}) int { return len(s) }, lengthMsgs{ + code: "slice", required: sliceRequiredKey, minKey: sliceMinLenKey, maxKey: sliceMaxLenKey, + minWord: "minItems", maxWord: "maxItems", unique: true, + }) +} + +// lengthMsgs are the codes, the messages and the keywords of JSON Schema of the rules of the length. +type lengthMsgs struct { + code, required, minKey, maxKey, minWord, maxWord string + // unique is true for slices, unique is checked by the elements + unique bool +} + +func lengthRules[C any](t tagContext, ptr bool, rules []tagRule, length func(c C) int, m lengthMsgs) error { + f := valueField[C](t, ptr) + check := func(ok func(n int) bool, msg shared.Msg) { + f.Custom(func(ctx context.Context, h *shared.FieldCustomHelper, c C) []shared.Error { + if n := length(c); !ok(n) { + return []shared.Error{h.ErrorMsg(ctx, n, msg)} + } + return nil + }) + } + for _, r := range rules { + switch r.name { + case "omitempty": + f = f.When(func(_ context.Context, c C) bool { return length(c) > 0 }) + case "unique": + if !m.unique { + return unsupported(r) + } + case "required": + msg := shared.M(m.code+".required", m.required) + f.Schema(shared.KeywordRequired, true).Schema(m.minWord, 1) + // 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": + 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))) + } + default: + return unsupported(r) + } + } + return nil +} + +// valueField returns the rules of the value of the field of type V or *V, a nil pointer is absent. +func valueField[V any](t tagContext, ptr bool) *shared.Field[V] { + if ptr { + return shared.Deref(shared.NewValueField[*V](t.field, t.h, t.fields, t.add, t.describe)) + } + return shared.NewValueField[V](t.field, t.h, t.fields, t.add, t.describe) +} + +// kindTags applies the rules of the values of one type. +type kindTags interface { + // value applies the rules to the field of the type or of a pointer to it + 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 + // unique checks that the slice field has no duplicates + unique(t tagContext) +} + +// typedTags is kindTags of the values of type V by the rules of apply. +type typedTags[V comparable] struct { + apply func(t tagContext, f *shared.Field[V], optional bool, rules []tagRule) error +} + +func (k typedTags[V]) value(t tagContext, ptr bool, rules []tagRule) error { + return k.applyValue(t, valueField[V](t, ptr), ptr, rules) +} + +func (k typedTags[V]) elems(t tagContext, ptr bool, rules []tagRule) error { + t.elem = true + s := shared.NewSliceFieldConfigurator[V](t.field, t.h, t.fields, t.add, t.describe) + return k.applyValue(t, s.EachField(), ptr, rules) +} + +func (k typedTags[V]) values(t tagContext, rules []tagRule) error { + t.elem = true + 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) + }) + return err +} + +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]) applyValue(t tagContext, f *shared.Field[V], optional bool, rules []tagRule) error { + for i, r := range rules { + if 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 + } + } + return k.apply(t, f, optional, rules) +} + +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]}, +} + +var timeTags = typedTags[time.Time]{apply: timeRules} + +// stringRules are the string rules without a parameter. +var stringRules = map[string]func(c *str.BaseConfigurator) *str.BaseConfigurator{ + "required": (*str.BaseConfigurator).Required, + "email": (*str.BaseConfigurator).Email, + "url": (*str.BaseConfigurator).URL, + "http_url": (*str.BaseConfigurator).URL, + "uuid": (*str.BaseConfigurator).UUID, + "ip": (*str.BaseConfigurator).IP, + "ipv4": (*str.BaseConfigurator).IPv4, + "ipv6": (*str.BaseConfigurator).IPv6, + "hostname": (*str.BaseConfigurator).Hostname, + "hostname_rfc1123": (*str.BaseConfigurator).Hostname, + "alphanum": (*str.BaseConfigurator).Alphanumeric, + "ascii": (*str.BaseConfigurator).ASCII, + "lowercase": (*str.BaseConfigurator).Lowercase, + "uppercase": (*str.BaseConfigurator).Uppercase, + "e164": (*str.BaseConfigurator).E164, + "base64": (*str.BaseConfigurator).Base64, + "base64url": (*str.BaseConfigurator).Base64URL, + "json": (*str.BaseConfigurator).JSON, + "semver": (*str.BaseConfigurator).Semver, + "cidr": (*str.BaseConfigurator).CIDR, + "mac": (*str.BaseConfigurator).MAC, + "hexcolor": (*str.BaseConfigurator).HexColor, + "iso3166_1_alpha2": (*str.BaseConfigurator).CountryCode, + "iso4217": (*str.BaseConfigurator).CurrencyCode, + "credit_card": (*str.BaseConfigurator).CreditCard, + "luhn_checksum": (*str.BaseConfigurator).Luhn, +} + +func stringTags(t tagContext, f *shared.Field[string], _ bool, rules []tagRule) error { + c := str.NewBaseConfigurator(f) + for _, r := range rules { + if rule, ok := stringRules[r.name]; ok { + rule(c) + continue + } + switch r.name { + case "min", "max", "len": + n, err := strconv.Atoi(r.param) + if err != nil { + return fmt.Errorf("%s=%s: %w", r.name, r.param, err) + } + if r.name != "max" { + c.MinRunes(n) + } + if r.name != "min" { + c.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": + other, err := otherField[string](t, r) + if err != nil { + return err + } + c.EqualField(other) + default: + return unsupported(r) + } + } + return nil +} + +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" { + return unsupported(r) + } + c.Required() + } + return nil +} + +func numberTags[N num.Number](t tagContext, f *shared.Field[N], optional bool, rules []tagRule) error { + c := num.NewBaseConfigurator(f, optional) + for _, r := range rules { + switch r.name { + case "required": + c.Required() + case "latitude": + c.Latitude() + case "longitude": + c.Longitude() + case "min", "gte", "max", "lte", "eq": + n, err := parseNumber[N](r.param) + if err != nil { + return fmt.Errorf("%s=%s: %w", r.name, r.param, err) + } + switch r.name { + case "min", "gte": + c.Min(n) + case "max", "lte": + c.Max(n) + default: + c.AnyOf(n) + } + case "oneof": + var allowed []N + for _, p := range strings.Fields(r.param) { + n, err := parseNumber[N](p) + if err != nil { + return fmt.Errorf("oneof=%s: %w", r.param, err) + } + allowed = append(allowed, n) + } + c.AnyOf(allowed...) + case "gtefield", "ltefield": + other, err := otherField[N](t, r) + if err != nil { + return err + } + if r.name == "gtefield" { + c.MinField(other) + } else { + c.MaxField(other) + } + default: + return unsupported(r) + } + } + return nil +} + +// parseNumber parses the number of the type N: an integer for the integer types. +func parseNumber[N num.Number](s string) (N, error) { + switch reflect.TypeFor[N]().Kind() { + case reflect.Float32, reflect.Float64: + f, err := strconv.ParseFloat(s, 64) + return N(f), err + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + u, err := strconv.ParseUint(s, 10, int(reflect.TypeFor[N]().Bits())) + return N(u), err + default: + i, err := strconv.ParseInt(s, 10, int(reflect.TypeFor[N]().Bits())) + return N(i), err + } +} + +func timeRules(t tagContext, f *shared.Field[time.Time], _ bool, rules []tagRule) error { + c := timex.NewBaseConfigurator(f) + for _, r := range rules { + switch r.name { + case "required": + c.Required() + case "gtfield", "ltfield": + other, err := otherField[time.Time](t, r) + if err != nil { + return err + } + if r.name == "gtfield" { + c.AfterField(other) + } else { + c.BeforeField(other) + } + default: + return unsupported(r) + } + } + 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 + if parent := t.field.GetParent(); parent != nil { + path = parent.GetStructPath() + "." + path + } + other, ok := t.storage.Find(path) + if !ok { + return nil, fmt.Errorf("%s=%s: no field %s", r.name, r.param, path) + } + 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 (*V)(reflect.ValueOf(other.GetPtr(t.model)).UnsafePointer()), nil +} + +func unsupported(r tagRule) error { + return fmt.Errorf("the rule %s isn't supported for the field, use the rules in code", r.name) +} diff --git a/tags_test.go b/tags_test.go new file mode 100644 index 0000000..f134202 --- /dev/null +++ b/tags_test.go @@ -0,0 +1,275 @@ +package valigo + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/assert" + + "github.com/insei/valigo/internal/testenv" + "github.com/insei/valigo/str" +) + +type tagsAddress struct { + City string `validate:"required,max=8"` +} + +// tagsPair compares the fields of a nested struct. +type tagsPair struct { + A string + B string `validate:"eqfield=A"` +} + +type tagsStatus string + +type tagsModel struct { + Name string `validate:"required,min=2,max=4"` + Code tagsStatus `validate:"oneof=new done"` + Email *string `validate:"omitempty,email"` + Nick string `validate:"omitempty,alphanum,len=3"` + Password string `validate:"required"` + Confirm string `validate:"eqfield=Password"` + Site string `validate:"startswith=https://,endswith=.com,contains=ex,url"` + Day string `validate:"datetime=2006-01-02"` + Kind string `validate:"eq=person"` + Age int `validate:"gte=18,lte=120"` + Min uint8 `validate:"min=1,max=9"` + Score *float64 `validate:"required,oneof=1.5 2.5"` + Level int64 `validate:"eq=3"` + Lat float32 `validate:"latitude"` + Lng float64 `validate:"longitude"` + Low int `validate:"ltefield=Age"` + High int `validate:"gtefield=Age"` + Agree bool `validate:"required"` + StartsAt time.Time `validate:"required"` + EndsAt time.Time `validate:"gtfield=StartsAt"` + BeforeAt *time.Time `validate:"ltfield=StartsAt"` + Tags []string `validate:"required,max=2,dive,required,max=3"` + Roles []string `validate:"unique"` + Nums []*int `validate:"min=1,dive,min=1"` + Times []time.Time `validate:"dive,required"` + Labels map[string]string `validate:"omitempty,max=1,dive,lowercase"` + Counts *map[string]int `validate:"required"` + Items []tagsAddress `validate:"len=1"` + Address tagsAddress + Home *tagsAddress `validate:"required"` + Ignored string `validate:"-"` + Untagged string + Skipped *[]string `validate:"omitempty,min=2"` + Optional *tagsAddress `validate:"omitempty"` + Pair tagsPair +} + +func validTagsModel() *tagsModel { + email, score, n := "a@b.cc", 1.5, 1 + starts := time.Date(2026, 1, 2, 0, 0, 0, 0, time.UTC) + before := starts.Add(-time.Hour) + counts := map[string]int{"a": 1} + return &tagsModel{ + Name: "Ann", Code: "new", Email: &email, Password: "p", Confirm: "p", Site: "https://ex.com", Day: "2026-01-02", + Kind: "person", Age: 30, Min: 1, Score: &score, Level: 3, Low: 30, High: 30, Agree: true, + StartsAt: starts, EndsAt: starts.Add(time.Hour), BeforeAt: &before, + Tags: []string{"go"}, Roles: []string{"a", "b"}, Nums: []*int{&n}, Times: []time.Time{starts}, + Labels: map[string]string{"a": "x"}, Counts: &counts, Items: []tagsAddress{{City: "x"}}, + Address: tagsAddress{City: "Paris"}, Home: &tagsAddress{City: "Rome"}, + } +} + +func newTagsValidator() *Validator { + v := New() + Configure[tagsModel](v, func(b Configurator[tagsModel], m *tagsModel) { + b.Tags("validate") + b.Field(&m.Untagged).As(str.Of).MaxLen(1) // the rules in code with the tags + }) + return v +} + +func TestTags(t *testing.T) { + v := newTagsValidator() + ctx := context.Background() + assert.Empty(t, v.ValidateTyped(ctx, validTagsModel())) + + zero := 0 + bad := &tagsModel{ + Name: "A", Code: "old", Nick: "a b", Confirm: "x", Site: "ftp://a.org", Day: "02.01.2026", Kind: "robot", + Age: 17, Min: 10, Level: 4, Lat: 91, Lng: 181, Low: 18, High: 16, + EndsAt: time.Time{}.Add(-time.Hour), Tags: []string{"", "long", "x"}, Roles: []string{"a", "a"}, + Nums: []*int{&zero, nil}, Times: []time.Time{{}}, Labels: map[string]string{"A": "B", "c": "d"}, + Items: []tagsAddress{}, Address: tagsAddress{City: "Amsterdam"}, Untagged: "ab", Skipped: &[]string{"a"}, + Pair: tagsPair{A: "a", B: "b"}, + } + var got []string + for _, err := range v.ValidateTyped(ctx, bad) { + got = append(got, err.Location+" "+err.Code) + } + assert.Equal(t, []string{ + "Name string.min_runes", + "Code string.any_of", + "Nick string.alphanumeric", + "Password string.required", + "Confirm string.equal_field", + "Site string.prefix", "Site string.suffix", "Site string.contains", + "Day string.datetime", + "Kind string.any_of", + "Age number.min", + "Min number.max", + "Score number.required", + "Level number.any_of", + "Lat number.latitude", + "Lng number.longitude", + "Low number.max_field", + "High number.min_field", + "Agree value.required", + "StartsAt time.required", + "EndsAt time.after_field", + "Tags slice.max_len", "Tags[0] string.required", "Tags[1] string.max_runes", + "Roles value.unique", + "Nums[0] number.min", + "Times[0] time.required", + "Labels map.max_len", "Labels[A] string.lowercase", + "Counts map.required", + "Items slice.min_len", + "Address.City string.max_runes", + "Home value.required", + "Skipped slice.min_len", + "Pair.B string.equal_field", + "Untagged string.max_len", + }, got) + + empty := map[string]int{} + model := validTagsModel() + model.Counts, model.Tags = &empty, nil + var errs []string + for _, err := range v.ValidateTyped(ctx, model) { + errs = append(errs, err.Location+" "+err.Code) + assert.Equal(t, 0, err.Value, "the errors of the lengths have the lengths") + } + assert.Equal(t, []string{"Tags slice.required", "Counts map.required"}, errs) + + model = validTagsModel() + model.Home.City = "" + errsOfHome := v.ValidateTyped(ctx, model) + if assert.Len(t, errsOfHome, 1) { + assert.Equal(t, "Home.City", errsOfHome[0].Location, "the fields of a present nested struct are validated") + } + + if !testenv.RaceEnabled { + valid := validTagsModel() + assert.Zero(t, testing.AllocsPerRun(10, func() { v.ValidateTyped(ctx, valid) })) + } +} + +func TestTagsConstraints(t *testing.T) { + var got []string + for _, c := range newTagsValidator().Constraints() { + if c.Field.GetStructPath() == "Tags" || c.Field.GetStructPath() == "Labels" || c.Field.GetStructPath() == "Home" { + got = append(got, c.Field.GetStructPath()+" "+c.Keyword) + } + } + assert.Equal(t, []string{ + "Tags required", "Tags minItems", "Tags maxItems", "Tags required", "Tags minLength", "Tags maxLength", + "Home required", + }, got, "omitempty rules aren't described") +} + +func TestTagsErrors(t *testing.T) { + tests := []struct { + name string + configure func() + err string + }{ + {"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`}, + {"bad oneof", tagsOf[struct { + A uint `validate:"oneof=1 -2"` + }], `valigo: tag validate:"oneof=1 -2" of field A: oneof=1 -2: strconv.ParseUint: parsing "-2": invalid syntax`}, + {"bad float", tagsOf[struct { + A float64 `validate:"max=y"` + }], `valigo: tag validate:"max=y" of field A: max=y: strconv.ParseFloat: parsing "y": invalid syntax`}, + {"bad length", tagsOf[struct { + A string `validate:"len=z"` + }], `valigo: tag validate:"len=z" of field A: len=z: strconv.Atoi: parsing "z": invalid syntax`}, + {"bad slice length", tagsOf[struct { + A []string `validate:"max=z"` + }], `valigo: tag validate:"max=z" of field A: max=z: strconv.Atoi: parsing "z": invalid syntax`}, + {"slice rule", tagsOf[struct { + A []string `validate:"email"` + }], `valigo: tag validate:"email" of field A: the rule email isn't supported for the field, use the rules in code`}, + {"unique of a map", tagsOf[struct { + A map[string]int `validate:"unique"` + }], `valigo: tag validate:"unique" of field A: the rule unique isn't supported for the field, use the rules in code`}, + {"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 valigo.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`}, + {"element rule", tagsOf[struct { + A []string `validate:"dive,isbn"` + }], `valigo: tag validate:"dive,isbn" of field A: the rule isbn isn't supported for the field, use the rules in code`}, + {"map value rule", tagsOf[struct { + A map[string]string `validate:"dive,isbn"` + }], `valigo: tag validate:"dive,isbn" of field A: the rule isbn isn't supported for the field, use the rules in code`}, + {"field of an element", tagsOf[struct { + A []string `validate:"dive,eqfield=B"` + B string + }], `valigo: tag validate:"dive,eqfield=B" of field A: eqfield isn't supported for the elements`}, + {"no field", tagsOf[struct { + A string `validate:"eqfield=B"` + }], `valigo: tag validate:"eqfield=B" of field A: eqfield=B: no field B`}, + {"other type", tagsOf[struct { + A int `validate:"gtefield=B"` + B string + }], `valigo: tag validate:"gtefield=B" of field A: gtefield=B: the field B has type string, int expected`}, + {"time field", tagsOf[struct { + A time.Time `validate:"gtfield=B"` + }], `valigo: tag validate:"gtfield=B" of field A: gtfield=B: no field B`}, + {"time rule", tagsOf[struct { + A time.Time `validate:"min=1"` + }], `valigo: tag validate:"min=1" of field A: the rule min isn't supported for the field, use the rules in code`}, + {"string field of a number", tagsOf[struct { + A string `validate:"eqfield=B"` + B int + }], `valigo: tag validate:"eqfield=B" of field A: eqfield=B: the field B has type int, string expected`}, + {"number rule", tagsOf[struct { + A int `validate:"email"` + }], `valigo: tag validate:"email" of field A: the rule email isn't supported for the field, use the rules in code`}, + {"bool rule", tagsOf[struct { + A bool `validate:"min=1"` + }], `valigo: tag validate:"min=1" of field A: the rule min isn't supported for the field, use the rules in code`}, + {"struct rule", tagsOf[struct { + A tagsAddress `validate:"required"` + }], `valigo: tag validate:"required" of field A: the rule required isn't supported for the field, use the rules in code`}, + {"type", tagsOf[struct { + A complex64 `validate:"required"` + }], `valigo: tag validate:"required" of field A: the fields of type complex64 aren't supported`}, + {"number field", tagsOf[struct { + A int `validate:"ltefield=B"` + B string + }], `valigo: tag validate:"ltefield=B" of field A: ltefield=B: the field B has type string, int expected`}, + {"elements of a type", tagsOf[struct { + A []complex64 `validate:"dive,required"` + }], `valigo: tag validate:"dive,required" of field A: the elements of type complex64 aren't supported, configure the rules of their type`}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.PanicsWithValue(t, tt.err, tt.configure) + }) + } +} + +// tagsOf configures the tags of T. +func tagsOf[T any]() { + Configure[T](New(), func(b Configurator[T], _ *T) { b.Tags("validate") }) +} From 9aabf5cf8c30215eebbb597305427f2200fa7f48 Mon Sep 17 00:00:00 2001 From: Dmitri Aleksandrov Date: Mon, 19 Oct 2026 11:42:37 +0300 Subject: [PATCH 3/4] test(bench): benchmark valigo by the tags of go-playground/validator --- bench/bench_test.go | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/bench/bench_test.go b/bench/bench_test.go index dda8f16..b25dfd2 100644 --- a/bench/bench_test.go +++ b/bench/bench_test.go @@ -60,6 +60,13 @@ func newValigo() *valigo.Validator { return v } +// newValigoTags configures valigo by the tags of go-playground/validator. +func newValigoTags() *valigo.Validator { + v := valigo.New() + valigo.Configure[User](v, func(b valigo.Configurator[User], _ *User) { b.Tags("validate") }) + return v +} + func TestTheSameRules(t *testing.T) { ctx := context.Background() v, pg := newValigo(), playground.New() @@ -76,6 +83,13 @@ func TestTheSameRules(t *testing.T) { if errs := v.Validate(ctx, invalid); len(errs) != 6 { t.Errorf("valigo: %d errors: %v", len(errs), errs) } + tags := newValigoTags() + if errs := tags.Validate(ctx, valid); errs != nil { + t.Errorf("valigo tags: %v", errs) + } + if errs := tags.Validate(ctx, invalid); len(errs) != 6 { + t.Errorf("valigo tags: %d errors: %v", len(errs), errs) + } if errs, _ := pg.Struct(invalid).(playground.ValidationErrors); len(errs) != 6 { t.Errorf("go-playground/validator: %d errors: %v", len(errs), errs) } @@ -93,6 +107,13 @@ func BenchmarkValid(b *testing.B) { _ = v.Validate(ctx, valid) } }) + b.Run("valigo-tags", func(b *testing.B) { + v := newValigoTags() + b.ReportAllocs() + for b.Loop() { + _ = v.Validate(ctx, valid) + } + }) b.Run("go-playground", func(b *testing.B) { v := playground.New() b.ReportAllocs() @@ -117,6 +138,13 @@ func BenchmarkInvalid(b *testing.B) { _ = v.Validate(ctx, invalid) } }) + b.Run("valigo-tags", func(b *testing.B) { + v := newValigoTags() + b.ReportAllocs() + for b.Loop() { + _ = v.Validate(ctx, invalid) + } + }) b.Run("go-playground", func(b *testing.B) { v := playground.New() b.ReportAllocs() From ac4872f6973b0c7e8165e6a170d442edc993841e Mon Sep 17 00:00:00 2001 From: Dmitri Aleksandrov Date: Mon, 19 Oct 2026 11:42:37 +0300 Subject: [PATCH 4/4] docs: describe the rules from tags --- README.md | 3 +- docs/features/index.md | 1 + docs/features/tags.md | 83 ++++++++++++++++++++++++++++++++++++++++++ docs/performance.md | 1 + mkdocs.yml | 2 + skills/valigo/SKILL.md | 4 ++ 6 files changed, 92 insertions(+), 2 deletions(-) create mode 100644 docs/features/tags.md diff --git a/README.md b/README.md index 696e9d1..b489b5f 100644 --- a/README.md +++ b/README.md @@ -73,6 +73,7 @@ and a conversion that doesn't fit the field doesn't compile: - **Conditions and custom rules**: `When` and `Custom` on fields and on the struct, closures with the context of the request — the limits can come from a database or the settings of a tenant. - **Absent values**: nil pointers and the fields of nil nested structs are skipped by every rule except `Required`. - **Your types**: a conversion function of a few lines, the core has no dependencies on uuid or other packages of types. +- **Tags of go-playground/validator**: `b.Tags("validate")` configures the rules of `validate:"required,max=64"` with the messages and the speed of valigo, a migration moves them to code one by one. # Errors and translations * Every error has the translated message, the location (`Tags[1]`, `address.city` with JSON paths), the value, a stable `Code` and named `Params` @@ -91,5 +92,3 @@ The same struct and rules, Intel Core i9-14900HX, Go 1.27.0, see [Performance](h | go-playground/validator | 1 785 ns, 16 allocs | 4 150 ns, 69 allocs, with `Error()` | | ozzo-validation | 2 950 ns, 38 allocs | 12 665 ns, 140 allocs, with `Error()` | -# Roadmap -* [ ] Rules from tags diff --git a/docs/features/index.md b/docs/features/index.md index 88af6de..8963336 100644 --- a/docs/features/index.md +++ b/docs/features/index.md @@ -14,6 +14,7 @@ How the rules are configured and composed. | [Conditions](conditions.md) | `When` on the struct and on a field, conditional requiredness | | [Custom rules](custom.md) | `Custom` on a field, on a slice and on the struct, rules with limits from data | | [Rules on other fields](fields.md) | `EqualField`, `MinField`, `MaxField`, `BeforeField`, `AfterField` by the pointer of the other field | +| [Rules from tags](tags.md) | `Tags`: the tags of go-playground/validator, `validate:"required,max=64"`, for a migration | ## Rules diff --git a/docs/features/tags.md b/docs/features/tags.md new file mode 100644 index 0000000..1809fbe --- /dev/null +++ b/docs/features/tags.md @@ -0,0 +1,83 @@ +# Rules from tags + +`b.Tags("validate")` configures the rules of the tags of the fields of the struct and of its nested structs in the syntax of [go-playground/validator](https://github.com/go-playground/validator): `validate:"required,max=64"`. It is for a migration: the structs keep their tags, and the rules move to code one by one — the tags and the rules in code are mixed in one `Configure`. + +The rules of the tags are the rules of valigo: the same messages in the languages of the users, the [codes](errors.md#codes-for-clients), the [JSON Schema](schema.md) and the speed — a valid object is validated without allocations, see [Performance](../performance.md). + +## Example + +```go +package main + +import ( + "context" + "fmt" + + "github.com/insei/valigo" + "github.com/insei/valigo/str" +) + +type Address struct { + City string `validate:"required,max=32"` +} + +type SignUp struct { + Email string `validate:"required,email"` + Password string `validate:"required,min=8"` + Confirm string `validate:"eqfield=Password"` + Age int `validate:"omitempty,gte=18,lte=120"` + Tags []string `validate:"max=3,dive,required,max=16"` + Address *Address // the rules of City apply when the address is present + Nick string +} + +func main() { + v := valigo.New() + valigo.Configure[SignUp](v, func(b valigo.Configurator[SignUp], s *SignUp) { + b.Tags("validate") + // the rules in code with the tags + b.Field(&s.Nick).As(str.Of).Trim().Alphanumeric() + }) + + errs := v.ValidateTyped(context.Background(), &SignUp{ + Email: "ann", Password: "secret", Confirm: "secrets", Age: 16, Tags: []string{"go", ""}, Nick: " a b ", + }) + for _, err := range errs { + fmt.Println(err.Location, "-", err.Message, "-", err.Code) + } +} +``` + +Output: + +```text +Email - Should be email address - string.email +Password - Cannot be shorter than 8 characters - string.min_runes +Confirm - Should be equal to Password - string.equal_field +Age - Cannot be less than 18 - number.min +Tags[1] - Should be fulfilled - string.required +Nick - Should contain only letters and digits - string.alphanumeric +``` + +## Rules + +| Fields | Rules | +|---|---| +| 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`. + +## 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. +- 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. diff --git a/docs/performance.md b/docs/performance.md index 8b91a4f..8d63ffa 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -39,6 +39,7 @@ An invalid object with 6 errors: valigo is about 1.4 times slower than the same rules written by hand on a valid object, it pays for the closures of the rules; it doesn't allocate either. The fields are read by the offsets of fmap without reflect, following the pointers of nested structs. Code generators of validators produce code like the hand-written one, so they are expected to be about as fast as it. +- The [rules from tags](features/tags.md) are the same rules: in one run a valid object took 392 ns by the tags of go-playground/validator and 373 ns by the rules in code, 0 allocations both; `max=64` is `MaxRunes`, `gte` and `lte` are two rules instead of one `AnyOfInterval`. - valigo builds the rules once in `Configure` and reads the fields by precomputed accessors, so valid objects cost no allocations; go-playground/validator parses the tags once too, but works through `reflect` on every call, ozzo-validation builds its rules on every call of `Validate`. - gookit/validate creates a validation per call, it is its API, and reports the errors of the elements of a slice under one key `Tags.*`; zog builds the messages of its issues. - valigo builds the translated messages of the errors at once, go-playground/validator returns the errors without messages and builds them by `Error` or `Translate`: compare valigo with the row "with `Error()`". diff --git a/mkdocs.yml b/mkdocs.yml index 3c882b4..301890f 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -84,6 +84,7 @@ nav: - Conditions: features/conditions.md - Custom rules: features/custom.md - Rules on other fields: features/fields.md + - Rules from tags: features/tags.md - Rules: - Strings: features/strings.md - Numbers: features/numbers.md @@ -135,6 +136,7 @@ plugins: - features/conditions.md: When on the struct and on fields, conditional requiredness - features/custom.md: Custom rules, rules from data - features/fields.md: rules on other fields + - features/tags.md: the rules of the tags of go-playground/validator, a migration from it Rules: - features/strings.md: the rules and formats of strings - features/numbers.md: the rules of numbers diff --git a/skills/valigo/SKILL.md b/skills/valigo/SKILL.md index 9c5f209..1cbd3aa 100644 --- a/skills/valigo/SKILL.md +++ b/skills/valigo/SKILL.md @@ -178,6 +178,10 @@ func main() { `valigo.New(valigo.WithErrorsTransformer(problem.Transformer()))` makes `Validate` return one `*problem.Details` of RFC 9457, write it by `problem.From(errs).Write(w)`: 422, `application/problem+json`, `errors` with `detail`, `pointer` (`#/tags/1`), `location`, `code`, `params`. Options: `problem.WithType`, `WithTitle`, `WithStatus`, `WithDetail`. +## 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). + ## JSON Schema `v.Constraints()` returns the unconditional rules as JSON Schema keywords (`shared.Constraint`: Struct, Field, Path `items`/`additionalProperties`/`propertyNames`, Keyword, Value); rules under `When` aren't described, after `Trim`/`Modify` only `required`. `vhuma.OpenAPI(api, v)` returns the huma document with them in the body schemas (huma's own schemas stay unchanged). Own conversions describe rules by `f.Schema("minimum", 0)`.