软件包版本如v9、v10:
软件包版本:v10
问题,问题或增强:当我试图运行下面的代码.我得到这个错误,这是有线
输出
Validation error: Key: 'Application.Applicants[0].Entity.Name' Error:Field validation for 'Name' failed on the 'required' tag
Key: 'Application.Applicants[0].Entity.TaxID' Error:Field validation for 'TaxID' failed on the 'required' tag
Key: 'Application.Applicants[1].Person.Name' Error:Field validation for 'Name' failed on the 'required' tag
Key: 'Application.Applicants[1].Person.Age' Error:Field validation for 'Age' failed on the 'required' tag
Key: 'Application.Applicants[1].Person.Email' Error:Field validation for 'Email' failed on the 'required' tag
字符集
- 代码示例,用于展示或复制:*
package main
import (
"fmt"
"github.com/go-playground/validator/v10"
)
type Application struct {
Applicants []Applicant `validate:"dive"`
}
type Applicant struct {
ApplicantCategory string `validate:"required,oneof=PERSON ENTITY"`
Person Person `validate:"required_if=ApplicantCategory PERSON"`
Entity Entity `validate:"required_if=ApplicantCategory ENTITY"`
}
type Person struct {
Name string `validate:"required"`
Age int `validate:"required,gte=18"`
Email string `validate:"required,email"`
}
type Entity struct {
Name string `validate:"required"`
TaxID string `validate:"required"`
}
func main() {
// Create a new validator instance
v := validator.New()
// Create an instance of Application to validate
data := Application{
Applicants: []Applicant{
{
ApplicantCategory: "PERSON",
Person: Person{
Name: "John Doe",
Age: 25,
Email: "[email protected]",
},
},
{
ApplicantCategory: "ENTITY",
Entity: Entity{
Name: "Example Corp",
TaxID: "123456789",
},
},
},
}
// Use the validator to validate the Application struct and its Applicants
if err := v.Struct(data); err != nil {
fmt.Println("Validation error:", err)
} else {
fmt.Println("Validation passed")
}
}
型
无法找到代码或验证程序包中的问题。任何帮助都将不胜感激...
1条答案
按热度按时间zkure5ic1#
添加
omitempty
,例如:字符集
playground中的完整示例(请注意,由于导入包的大小,此dos无法在playground中可靠运行)。
问题是
required_if
导致库检查Person
/Entity
是否存在,但库仍将验证空的Person
/Entity
添加omitempty
意味着库将忽略空的struct
;这提供了期望的结果,因为required_if
将确保任何所需的struct
不为空(意味着它将被验证)。另一种选择是使用指针(playground):
型
这里的区别是,当没有
Entity
时,值将是nil
(与具有默认值的Entity
相反),这意味着validator
没有任何东西需要验证。注:我建议使用
v := validator.New(validator.WithRequiredStructEnabled())
(根据文档)。