英文:
Can I conditional validate from parent struct value ? (https://github.com/go-playground/validator)
问题
我正在尝试使用https://github.com/go-playground/validator进行验证。
我遇到的问题是,条件验证取决于父结构的值。
首先,这种验证是否可行?
如果不行,你能给我一个解决这些问题的提示吗?
谢谢。
type A struct {
Enabled bool `json:"enabled" validate:"required"`
Reason struct {
Note string `json:"note" validate:"required_if=Enabled true"` // 如果父结构的Enabled为true,则该结构将是必需的
} `json:"reason" validate:"required"`
}
英文:
I'm trying to validate using https://github.com/go-playground/validator.
I'm facing problem that conditional validation depend on parent struct value.
First of all that validation can be done ?
If can not be, could you give me a hint that solve these problems.
Thanks.
type A struct {
Enabled bool `json:"enabled" validate:"required"`
Reason struct {
Note string `json:"note" validate:"required_if=Enabled true"` // if parent's Enabled is true that struct will be required
} `json:"reason" validate:"required"`
}
答案1
得分: 1
只需将Reason
定义为指针即可解决问题。
type A struct {
Enabled bool `json:"enabled" validate:"required"`
Reason *Reason `json:"reason" validate:"required_if=Enabled true"`
}
type Reason struct {
Note string `json:"note" validate:"required"`
}
另一种方法是自定义验证函数,可以参考这个链接:https://pkg.go.dev/github.com/go-playground/validator/v10#hdr-Custom_Validation_Functions
英文:
Just define Reason
as pointer so it will be fine.
type A struct {
Enabled bool `json:"enabled" validate:"required"`
Reason *Reason `json:"reason" validate:"required_if=Enabled true"`
}
type Reason struct {
Note string `json:"note" validate:"required"`
}
Another way: u can custom the validate https://pkg.go.dev/github.com/go-playground/validator/v10#hdr-Custom_Validation_Functions
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论