[gogf/gf]递归校验中对于 struct 校验异常

2024-06-25 798 views
0

对于递归校验,即使外层没有 required 也会递归到底层

func Test_Validation(t *testing.T) {
    ctx := context.Background()
    gtest.C(t, func(t *gtest.T) {
        type Student struct {
            Name string `v:"required"`
            Age  int
        }
        type Teacher struct {
            Students Student
        }
        var (
            teacher = Teacher{}
            data    = g.Map{
                "students": nil,
            }
        )
        err := g.Validator().Assoc(data).Data(teacher).Run(ctx)
        fmt.Println(err)
    })
}

而且,只要我有了同名的字段,即使不在结构体对应的层级上,也会校验通过

func Test_Validation(t *testing.T) {
    ctx := context.Background()
    gtest.C(t, func(t *gtest.T) {
        type Student struct {
            Name string `v:"required"`
        }
        type Teacher struct {
            Students Student
        }
        var (
            teacher = Teacher{}
            data    = g.Map{
                "name":     "john",   // 不在对应的层级上,但是校验通过了
                "students": nil,
            }
        )
        err := g.Validator().Assoc(data).Data(teacher).Run(ctx)
        fmt.Println(err)
    })
}

不用校验内部的 Name

回答

8

@qq375251855 我看看。

0

@qq375251855 针对第一个case,是因为你的Student属性是个空结构体,是带有默认值的。递归校验里面,虽然Student不是必须参数,这个意思是你可以不传递,但是只要传递了就会按照里面属性的校验规则执行校验。可以对比和以下代码的差别:

package main

import (
    "context"
    "fmt"

    "github.com/gogf/gf/v2/frame/g"
)

func main() {
    ctx := context.Background()
    type Student struct {
        Name string `v:"required"`
        Age  int
    }
    type Teacher struct {
        Students *Student
    }
    var (
        teacher = Teacher{}
        data    = g.Map{
            "students": nil,
        }
    )
    err := g.Validator().Assoc(data).Data(teacher).Run(ctx)
    fmt.Println(err)
}
2

@qq375251855 第2个case是个bug,我已修复,感谢反馈。

7

感谢!

8

按照这种方式,可以避免底层结构体 Student 的校验被触发

package main

import (
    "context"
    "fmt"

    "github.com/gogf/gf/v2/frame/g"
)

func main() {
    ctx := context.Background()
    type Student struct {
        Name string `v:"required"`
        Age  int
    }
    type Teacher struct {
        Students *Student
    }
    var (
        teacher = Teacher{}
        data    = g.Map{
            "students": nil,
        }
    )
    err := g.Validator().Assoc(data).Data(teacher).Run(ctx)
    fmt.Println(err)
}

但是很不幸,即使我传递了完整的 Student 也不会触发校验

package main

import (
    "context"
    "fmt"

    "github.com/gogf/gf/v2/frame/g"
)

func main() {
    ctx := context.Background()
    type Student struct {
        Name string `v:"required|size:32"`
        Age  int
    }
    type Teacher struct {
        Students *Student
    }
    var (
        teacher = Teacher{}
        data    = g.Map{
            "students": g.Map{
                "name": "1",
            },
        }
    )
    err := g.Validator().Assoc(data).Data(teacher).Run(ctx)
    fmt.Println(err)
}