Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,19 @@ func (c Configurator[T]) add(fn shared.ValidationFn) {
c.b.v.validators[t] = append(c.b.v.validators[t], fn)
}

// describe returns the registration of the constraints of the rules of T, nil under the struct level When:
// the conditional rules aren't described.
func (c Configurator[T]) describe() shared.Describe {
if c.b.when != nil {
return nil
}
v, t := c.b.v, reflect.TypeFor[T]()
return func(constraint shared.Constraint) {
constraint.Struct = t
v.constraints[t] = append(v.constraints[t], constraint)
}
}

// When returns a Configurator whose rules are applied only if fn returns true.
// Conditions of chained When calls are combined with AND.
func (c Configurator[T]) When(fn func(ctx context.Context, obj *T) bool) Configurator[T] {
Expand Down Expand Up @@ -103,20 +116,20 @@ func (c Configurator[T]) Custom(fn func(ctx context.Context, h shared.StructCust
// b.Field(&m.Name).As(str.Of), b.Field(&m.Discount).As(num.Ptr).
func (c Configurator[T]) Field[F any](fieldPtr *F) *shared.Field[F] {
field := c.field(fieldPtr)
return shared.NewValueField[F](field, c.b.v.helper, c.field, c.add)
return shared.NewValueField[F](field, c.b.v.helper, c.field, c.add, c.describe())
}

// Slice returns the configurator of the slice field with the rules of the slice itself,
// convert it to a typed one with As for the rules of elements: b.Slice(&m.Tags).As(str.Slice).
// A pointer to a slice field is converted from its field: b.Field(&m.Tags).As(shared.SlicePtr).
func (c Configurator[T]) Slice[E any](sliceFieldPtr *[]E) *shared.SliceFieldConfigurator[E] {
field := c.field(sliceFieldPtr)
return shared.NewSliceFieldConfigurator[E](field, c.b.v.helper, c.field, c.add)
return shared.NewSliceFieldConfigurator[E](field, c.b.v.helper, c.field, c.add, c.describe())
}

// Map returns the configurator of the map field with the rules of the map itself, EachKey and EachValue:
// b.Map(&m.Labels).MaxLen(10).EachKey(func(k *shared.Field[string]) { k.As(str.Of).Hostname() }).
func (c Configurator[T]) Map[K comparable, V any](mapFieldPtr *map[K]V) *shared.MapFieldConfigurator[K, V] {
field := c.field(mapFieldPtr)
return shared.NewMapFieldConfigurator[K, V](field, c.b.v.helper, c.field, c.add)
return shared.NewMapFieldConfigurator[K, V](field, c.b.v.helper, c.field, c.add, c.describe())
}
123 changes: 123 additions & 0 deletions constraints_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
package valigo

import (
"context"
"reflect"
"regexp"
"testing"
"time"

"github.com/stretchr/testify/assert"

"github.com/insei/valigo/eq"
"github.com/insei/valigo/num"
"github.com/insei/valigo/shared"
"github.com/insei/valigo/str"
)

type constraintsAddress struct {
City string
}

type constraintsModel struct {
Name string
Code string
Email *string
Age int
Rate *float64
Role string
Kind string
Day string
Tags []string
Roles []string
Labels map[string]int
Note string
Address *constraintsAddress
}

type described struct {
Field string
Path []string
Keyword string
Value any
}

func describedOf(constraints []shared.Constraint) []described {
result := make([]described, len(constraints))
for i, c := range constraints {
result[i] = described{Field: c.Field.GetStructPath(), Path: c.Path, Keyword: c.Keyword, Value: c.Value}
}
return result
}

func TestConstraints(t *testing.T) {
v := New()
Configure[constraintsModel](v, func(b Configurator[constraintsModel], m *constraintsModel) {
b.Field(&m.Name).As(str.Of).Trim().Required().MaxRunes(64)
b.Field(&m.Code).As(str.Of).MinRunes(2).MaxLen(8).Regexp(regexp.MustCompile(`^[A-Z]+$`)).Prefix("A.")
b.Field(&m.Email).As(str.Of).Email()
b.Field(&m.Age).As(num.Of).Required().AnyOfInterval(18, 120)
b.Field(&m.Rate).As(num.Ptr).Min(0).Max(1)
b.Field(&m.Role).As(eq.Of).OneOf("admin", "user")
b.Field(&m.Kind).As(eq.Of).Equal("person")
b.Field(&m.Day).As(str.Of).Datetime(time.DateOnly).Datetime(time.Kitchen)
b.Slice(&m.Tags).As(str.Slice).Required().MaxLen(5).Each(func(tag *str.BaseConfigurator) { tag.MaxRunes(16) })
b.Slice(&m.Roles).As(eq.Slice).MinLen(1).Unique()
b.Map(&m.Labels).Required().MaxLen(3).
EachKey(func(k *shared.Field[string]) { k.As(str.Of).Hostname() }).
EachValue(func(v *shared.Field[int]) { v.As(num.Of).Min(1) })
b.Field(&m.Note).As(str.Of).When(func(context.Context, string) bool { return true }).MaxLen(10)
b.Field(&m.Address.City).As(str.Of).Required()
b.When(func(context.Context, *constraintsModel) bool { return true }).Field(&m.Note).As(str.Of).MaxLen(20)
})
items, props, names := []string{"items"}, []string{"additionalProperties"}, []string{"propertyNames"}
assert.Equal(t, []described{
{"Name", nil, "required", true},
{"Code", nil, "minLength", 2},
{"Code", nil, "maxLength", 8},
{"Code", nil, "pattern", "^[A-Z]+$"},
{"Code", nil, "pattern", `^A\.`},
{"Email", nil, "format", "email"},
{"Age", nil, "required", true},
{"Age", nil, "minimum", 18},
{"Age", nil, "maximum", 120},
{"Rate", nil, "minimum", 0.0},
{"Rate", nil, "maximum", 1.0},
{"Role", nil, "enum", []any{"admin", "user"}},
{"Kind", nil, "const", "person"},
{"Day", nil, "format", "date"},
{"Tags", nil, "required", true},
{"Tags", nil, "minItems", 1},
{"Tags", nil, "maxItems", 5},
{"Tags", items, "maxLength", 16},
{"Roles", nil, "minItems", 1},
{"Roles", nil, "uniqueItems", true},
{"Labels", nil, "required", true},
{"Labels", nil, "minProperties", 1},
{"Labels", nil, "maxProperties", 3},
{"Labels", names, "format", "hostname"},
{"Labels", props, "minimum", 1},
{"Address.City", nil, "required", true},
{"Address.City", nil, "minLength", 1},
}, describedOf(v.Constraints()))
for _, c := range v.Constraints() {
assert.Equal(t, reflect.TypeFor[constraintsModel](), c.Struct)
}

Configure[constraintsModel](v, func(b Configurator[constraintsModel], m *constraintsModel) {
b.Field(&m.Email).As(str.Of).Email()
})
assert.Len(t, v.Constraints(), 1, "Configure replaces the constraints")
}

func TestConstraintsOrder(t *testing.T) {
v := New()
Configure[constraintsModel](v, func(b Configurator[constraintsModel], m *constraintsModel) {
b.Field(&m.Name).As(str.Of).Required()
})
Configure[constraintsAddress](v, func(b Configurator[constraintsAddress], a *constraintsAddress) {
b.Field(&a.City).As(str.Of).Required()
})
assert.Equal(t, "City", v.Constraints()[0].Field.GetStructPath(), "the structs are sorted by name")
assert.Equal(t, "Name", v.Constraints()[2].Field.GetStructPath())
}
3 changes: 3 additions & 0 deletions eq/base.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ func Ptr[T comparable](f *shared.Field[*T]) *BaseConfigurator[T] {

// Required checks if the value is not zero, for pointer fields checks if the pointer is not nil.
func (i *BaseConfigurator[T]) Required() *BaseConfigurator[T] {
i.f.Schema(shared.KeywordRequired, true)
optional := i.optional
var zero T
i.f.RequiredMsg(func(v T) bool { return optional || v != zero }, shared.M("value.required", requiredLocaleKey))
Expand All @@ -52,6 +53,7 @@ func (i *BaseConfigurator[T]) Required() *BaseConfigurator[T] {

// OneOf checks if the value is one of the allowed values.
func (i *BaseConfigurator[T]) OneOf(allowed ...T) *BaseConfigurator[T] {
i.f.Schema("enum", shared.Values(allowed))
i.f.CheckMsg(func(v T) bool { return slices.Contains(allowed, v) }, shared.M("value.one_of", oneOfLocaleKey, shared.P("values", allowed)))
return i
}
Expand All @@ -64,6 +66,7 @@ func (i *BaseConfigurator[T]) NotOneOf(forbidden ...T) *BaseConfigurator[T] {

// Equal checks if the value is equal to expected, e.g. Equal(true) for an accepted agreement.
func (i *BaseConfigurator[T]) Equal(expected T) *BaseConfigurator[T] {
i.f.Schema("const", expected)
i.f.CheckMsg(func(v T) bool { return v == expected }, shared.M("value.equal", equalLocaleKey, shared.P("value", expected)))
return i
}
Expand Down
1 change: 1 addition & 0 deletions eq/slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ func (s *SliceConfigurator[E]) OneOf(allowed ...E) *SliceConfigurator[E] {
// Unique checks that the slice has no duplicate elements, the error value is the first duplicate.
// Slices up to 32 elements are checked without allocations.
func (s *SliceConfigurator[E]) Unique() *SliceConfigurator[E] {
s.Slice().Schema("uniqueItems", true)
msg := shared.M("value.unique", uniqueLocaleKey)
s.Slice().Custom(func(ctx context.Context, h *shared.FieldCustomHelper, elems shared.Elems[E]) []shared.Error {
if dup, ok := duplicate(elems); ok {
Expand Down
7 changes: 7 additions & 0 deletions num/base.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,19 +49,22 @@ func Ptr[N Number](f *shared.Field[*N]) *BaseConfigurator[N] {

// Required checks if the number is not zero, for pointer fields checks if the pointer is not nil.
func (i *BaseConfigurator[N]) Required() *BaseConfigurator[N] {
i.f.Schema(shared.KeywordRequired, true)
optional := i.optional
i.f.RequiredMsg(func(v N) bool { return optional || v != 0 }, shared.M("number.required", requiredLocaleKey))
return i
}

// Max checks if the number is not greater than maxNum.
func (i *BaseConfigurator[N]) Max(maxNum N) *BaseConfigurator[N] {
i.f.Schema("maximum", maxNum)
i.f.CheckMsg(func(v N) bool { return v <= maxNum }, shared.M("number.max", maxLocaleKey, shared.P("max", maxNum)))
return i
}

// Min checks if the number is not less than minNum.
func (i *BaseConfigurator[N]) Min(minNum N) *BaseConfigurator[N] {
i.f.Schema("minimum", minNum)
i.f.CheckMsg(func(v N) bool { return v >= minNum }, shared.M("number.min", minLocaleKey, shared.P("min", minNum)))
return i
}
Expand All @@ -82,24 +85,28 @@ func (i *BaseConfigurator[N]) MaxField(other *N) *BaseConfigurator[N] {

// AnyOf checks if the number is one of the allowed values.
func (i *BaseConfigurator[N]) AnyOf(allowed ...N) *BaseConfigurator[N] {
i.f.Schema("enum", shared.Values(allowed))
i.f.CheckMsg(func(v N) bool { return slices.Contains(allowed, v) }, shared.M("number.any_of", anyOfLocaleKey, shared.P("values", allowed)))
return i
}

// AnyOfInterval checks if the number is within [begin, end] interval, both ends inclusive.
func (i *BaseConfigurator[N]) AnyOfInterval(begin, end N) *BaseConfigurator[N] {
i.f.Schema("minimum", begin).Schema("maximum", end)
i.f.CheckMsg(func(v N) bool { return v >= begin && v <= end }, shared.M("number.interval", anyOfIntervalLocalKey, shared.P("min", begin), shared.P("max", end)))
return i
}

// Latitude checks if the number is a latitude in degrees, within [-90, 90].
func (i *BaseConfigurator[N]) Latitude() *BaseConfigurator[N] {
i.f.Schema("minimum", -90).Schema("maximum", 90)
i.f.CheckMsg(func(v N) bool { return float64(v) >= -90 && float64(v) <= 90 }, shared.M("number.latitude", latitudeLocaleKey))
return i
}

// Longitude checks if the number is a longitude in degrees, within [-180, 180].
func (i *BaseConfigurator[N]) Longitude() *BaseConfigurator[N] {
i.f.Schema("minimum", -180).Schema("maximum", 180)
i.f.CheckMsg(func(v N) bool { return float64(v) >= -180 && float64(v) <= 180 }, shared.M("number.longitude", longitudeLocaleKey))
return i
}
Expand Down
8 changes: 4 additions & 4 deletions shared/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ func (s *SliceFieldConfigurator[E]) As[R any](conv func(s *SliceFieldConfigurato
// Use it in conversions of pointer fields, e.g. num.Ptr is num.Of of the dereferenced field.
func Deref[T any](f *Field[*T]) *Field[T] {
add := f.add
return &Field[T]{field: f.field, h: f.h, fields: f.fields, add: func(fn checkFn[T]) {
return &Field[T]{field: f.field, h: f.h, fields: f.fields, schema: f.schema, add: func(fn checkFn[T]) {
add(func(ctx context.Context, h Helper, obj any, v **T, errs []Error) []Error {
var p *T
if v != nil {
Expand All @@ -44,7 +44,7 @@ func Retype[T, U any](f *Field[T]) *Field[U] {
}
mustLayout[U](f.field, reflect.TypeFor[T]())
add := f.add
return &Field[U]{field: f.field, h: f.h, fields: f.fields, add: func(fn checkFn[U]) {
return &Field[U]{field: f.field, h: f.h, fields: f.fields, schema: f.schema, add: func(fn checkFn[U]) {
add(func(ctx context.Context, h Helper, obj any, v *T, errs []Error) []Error {
return fn(ctx, h, obj, (*U)(unsafe.Pointer(v)), errs)
})
Expand All @@ -57,7 +57,7 @@ func RetypeSlice[E, U any](s *SliceFieldConfigurator[E]) *SliceFieldConfigurator
if same, ok := any(s).(*SliceFieldConfigurator[U]); ok {
return same
}
return &SliceFieldConfigurator[U]{field: s.field, h: s.h, fields: s.fields, get: elemsGetter[U](s.field), add: s.add}
return &SliceFieldConfigurator[U]{field: s.field, h: s.h, fields: s.fields, get: elemsGetter[U](s.field), add: s.add, schema: s.schema}
}

// SlicePtr converts the field of a pointer to a slice, *[]E, to the slice configurator, a nil pointer is absent:
Expand All @@ -66,7 +66,7 @@ func SlicePtr[E any](f *Field[*[]E]) *SliceFieldConfigurator[E] {
if f.root == nil {
panic(fmt.Sprintf("valigo: SlicePtr of field %s must be called before When and other conversions", f.field.GetStructPath()))
}
return NewSliceFieldConfigurator[E](f.field, f.h, f.fields, f.root)
return NewSliceFieldConfigurator[E](f.field, f.h, f.fields, f.root, f.rootDescribe)
}

// SliceRules are the rules of the slice itself for the typed slice configurators, S is the type of the configurator.
Expand Down
22 changes: 11 additions & 11 deletions shared/convert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,54 +31,54 @@ func (t *typedSlice) NotEmpty() *typedSlice {

func TestFieldAs(t *testing.T) {
var r rules
f := NewValueField[string](sampleField(t, "Text"), pathHelper{}, sampleFields, r.add)
f := NewValueField[string](sampleField(t, "Text"), pathHelper{}, sampleFields, r.add, nil)
got := f.As(func(f *Field[string]) *Field[string] { return f.Check(notEmpty, "required") })
assert.Same(t, f, got)
assert.Len(t, r.validate(&sample{}), 1)
}

func TestDeref(t *testing.T) {
var r rules
NewValueField[*string](sampleField(t, "TextPtr"), pathHelper{}, sampleFields, r.add).As(Deref).Required(notEmpty, "required")
NewValueField[*string](sampleField(t, "TextPtr"), pathHelper{}, sampleFields, r.add, nil).As(Deref).Required(notEmpty, "required")
assert.Equal(t, []Error{{Location: "TextPtr", Message: "required"}}, r.validate(&sample{}), "nil pointer is absent")
assert.Equal(t, []Error{{Location: "TextPtr", Message: "required", Value: ""}}, r.validate(&sample{TextPtr: ptr("")}))
assert.Empty(t, r.validate(&sample{TextPtr: ptr("a")}))
}

func TestDerefOfNilNestedStruct(t *testing.T) {
var r rules
NewValueField[*string](sampleField(t, "Inner.TextPtr"), pathHelper{}, sampleFields, r.add).As(Deref).Check(notEmpty, "required")
NewValueField[*string](sampleField(t, "Inner.TextPtr"), pathHelper{}, sampleFields, r.add, nil).As(Deref).Check(notEmpty, "required")
assert.Empty(t, r.validate(&sample{}))
}

func TestRetype(t *testing.T) {
var r rules
named := NewValueField[label](sampleField(t, "Label"), pathHelper{}, sampleFields, r.add)
named := NewValueField[label](sampleField(t, "Label"), pathHelper{}, sampleFields, r.add, nil)
Retype[label, string](named).Check(func(v string) bool { return v == "ok" }, "bad")
assert.Equal(t, []Error{{Location: "Label", Message: "bad", Value: "no"}}, r.validate(&sample{Label: "no"}))

text := NewValueField[string](sampleField(t, "Text"), pathHelper{}, sampleFields, r.add)
text := NewValueField[string](sampleField(t, "Text"), pathHelper{}, sampleFields, r.add, nil)
assert.Same(t, text, Retype[string, string](text), "the same type isn't wrapped")
assert.PanicsWithValue(t, "valigo: field Num has type int, string expected", func() {
Retype[int, string](NewValueField[int](sampleField(t, "Num"), pathHelper{}, sampleFields, r.add))
Retype[int, string](NewValueField[int](sampleField(t, "Num"), pathHelper{}, sampleFields, r.add, nil))
})
}

func TestRetypeSlice(t *testing.T) {
var r rules
NewSliceFieldConfigurator[*string](sampleField(t, "TextPtrs"), pathHelper{}, sampleFields, r.add).As(toTypedSlice).Required().NotEmpty()
NewSliceFieldConfigurator[*string](sampleField(t, "TextPtrs"), pathHelper{}, sampleFields, r.add, nil).As(toTypedSlice).Required().NotEmpty()
assert.Equal(t, []Error{
{Location: "TextPtrs[1]", Message: "required"},
{Location: "TextPtrs[2]", Message: "required", Value: ""},
}, r.validate(&sample{TextPtrs: []*string{ptr("a"), nil, ptr("")}}))

texts := NewSliceFieldConfigurator[string](sampleField(t, "Texts"), pathHelper{}, sampleFields, r.add)
texts := NewSliceFieldConfigurator[string](sampleField(t, "Texts"), pathHelper{}, sampleFields, r.add, nil)
assert.Same(t, texts, RetypeSlice[string, string](texts), "the same type isn't wrapped")
}

func TestSlicePtr(t *testing.T) {
var r rules
NewValueField[*[]string](sampleField(t, "TextsPtr"), pathHelper{}, sampleFields, r.add).As(SlicePtr).As(toTypedSlice).MaxLen(1).NotEmpty()
NewValueField[*[]string](sampleField(t, "TextsPtr"), pathHelper{}, sampleFields, r.add, nil).As(SlicePtr).As(toTypedSlice).MaxLen(1).NotEmpty()
assert.Empty(t, r.validate(&sample{}), "nil pointer to slice is absent")
assert.Equal(t, []Error{
{Location: "TextsPtr", Message: "validation:slice:Cannot contain more than 1 elements", Value: 2},
Expand All @@ -88,7 +88,7 @@ func TestSlicePtr(t *testing.T) {

func TestSlicePtrAfterWhenPanics(t *testing.T) {
var r rules
f := NewValueField[*[]string](sampleField(t, "TextsPtr"), pathHelper{}, sampleFields, r.add)
f := NewValueField[*[]string](sampleField(t, "TextsPtr"), pathHelper{}, sampleFields, r.add, nil)
assert.PanicsWithValue(t, "valigo: SlicePtr of field TextsPtr must be called before When and other conversions", func() {
SlicePtr(f.When(func(context.Context, *[]string) bool { return true }))
})
Expand Down Expand Up @@ -117,7 +117,7 @@ func TestSliceRules(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var r rules
tt.setup(NewSliceFieldConfigurator[string](sampleField(t, "Texts"), pathHelper{}, sampleFields, r.add).As(toTypedSlice))
tt.setup(NewSliceFieldConfigurator[string](sampleField(t, "Texts"), pathHelper{}, sampleFields, r.add, nil).As(toTypedSlice))
assert.Equal(t, tt.want, r.validate(tt.obj))
})
}
Expand Down
Loading
Loading