Skip to content

Commit

Permalink
checker: nested struct validation
Browse files Browse the repository at this point in the history
  • Loading branch information
wuhan005 committed Aug 17, 2024
1 parent 3d1c094 commit 73512fa
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 4 deletions.
60 changes: 60 additions & 0 deletions checker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -737,3 +737,63 @@ func Test_UserDefinedError(t *testing.T) {
assert.Equal(t, "是错误的年龄呢~", errs[0].Error())
})
}

func Test_NestedStruct(t *testing.T) {
type order struct {
FieldUID string `valid:"required"`
OrderType string `valid:"list:asc,desc"`
}

type view struct {
Field string `valid:"required"`
Order order
}

t.Run("ok", func(t *testing.T) {
v := view{
Field: "name",
Order: order{
FieldUID: "name",
OrderType: "asc",
},
}

errs, ok := Check(v)
assert.True(t, ok)
assert.Equal(t, 0, len(errs))
})

t.Run("unexpected orderType", func(t *testing.T) {
v := view{
Field: "name",
Order: order{
FieldUID: "name",
OrderType: "123",
},
}

errs, ok := Check(v)
assert.False(t, ok)
assert.Equal(t, 1, len(errs))
assert.Equal(t, "OrderType不是一个有效的值", errs[0].Error())
})

t.Run("nested with tag", func(t *testing.T) {
type view struct {
Field string `valid:"required"`
Order order `valid:"required"`
}

v := view{
Field: "name",
Order: order{
FieldUID: "name",
OrderType: "asc",
},
}

errs, ok := Check(v)
assert.True(t, ok)
assert.Equal(t, 0, len(errs))
})
}
10 changes: 7 additions & 3 deletions govalid.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package govalid

import (
"golang.org/x/text/language"
"reflect"

"golang.org/x/text/language"
)

// Check checks the struct value.
Expand All @@ -23,10 +24,13 @@ func Check(v interface{}, lang ...language.Tag) (errs []*ErrContext, ok bool) {
structFields := parseStruct(structType, structValue, templateLanguage)

for _, field := range structFields {
field := field

fieldErrorMessage := field.errorMessage

for _, r := range field.rules {
rule := r
for _, rule := range field.rules {
rule := rule

checkerName := rule.checker
checkerContext := CheckerContext{
StructValue: structValue,
Expand Down
8 changes: 7 additions & 1 deletion parser.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
package govalid

import (
"golang.org/x/text/language"
"reflect"
"strings"

"golang.org/x/text/language"
)

var (
Expand Down Expand Up @@ -52,6 +53,11 @@ func parseStruct(structType reflect.Type, structValue reflect.Value, languageTag
}
}

// Check if the field is a struct.
if field.Type.Kind() == reflect.Struct {
fields = append(fields, parseStruct(field.Type, structValue.Field(i), languageTag)...)
}

// Check if this field has a validator tag.
rawRules, ok := field.Tag.Lookup(RulesField)
if !ok {
Expand Down

0 comments on commit 73512fa

Please sign in to comment.