gpt4 book ai didi

go - 检测失败的结构字段 - govalidator

转载 作者:IT王子 更新时间:2023-10-29 01:06:30 25 4
gpt4 key购买 nike

我正在试验 govalidator - https://github.com/asaskevich/govalidator

我想知道是否可以检测结构中的哪个字段未通过验证检查,以便我可以返回适当的错误消息。例如:

type Post struct {
Title string `valid:"alphanum,required"`
Message string `valid:"required"`
}

result, err := govalidator.ValidateStruct(post)
if err != nil {
//if title is missing then show error 1
//if message is missing then show error 2
}

最佳答案

这似乎类似于issue/67 :

At this moment it gives error like this:

Title: My123 does not validate as alpha;
AuthorIP: 123 does not validate as ipv4;

I create function ErroByField(e error, field string) that will return error for specified field of struct or empty string otherwise, I hope that it will be helpful.

For example:

type Post struct {
Title string `valid:"alpha,required"`
Message string `valid:"ascii"`
AuthorIP string `valid:"ipv4"`
}

post := &Post{"My123", "duck13126", "123"}
result, err := govalidator.ValidateStruct(post)

titleError := govalidator.ErrorByField(err, "Title")
if titleError != "" {
println(titleError) // -> My123 does not validate as alpha
}

关于go - 检测失败的结构字段 - govalidator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31906246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com