英文:
How to accept only one of multiple fields in Go Validator?
问题
type CoolName struct {
Foo string `json:"foo" validate:"required_without=Bar"`
Bar string `json:"bar" validate:"required_without=Foo"`
}
使用Go验证器,我想要只有这两个字段中的一个是必需的,并且如果这两个字段都有内容,则给出错误提示。
我使用了required_without
,但它只能确保其中一个字段是必需的。我无法弄清楚如何验证这两个字段在同时没有内容的情况下。
英文:
type CoolName struct {
Foo string `json:"foo"`
Bar string `json:"bar"`
}
With the Go validator, I want to make only one of these two fields required and give an error if the content of both fields is full.
I used required_without
but it only helps with requiring one of them. I can't figure out how can i validate if both fields doesn't have a content at the same time.
答案1
得分: 1
我已经按照这个链接的说明进行了操作,并且对我起作用了。
type Auth struct {
APIKey string `json:"apiKey" validate:"required_without=Username,required_without=Password"`
Username string `json:"username" validate:"required_without=APIKey"`
Password string `json:"password" validate:"required_without=APIKey"`
}
请注意,我只提供了代码的翻译部分,不包括其他内容。
英文:
i have follow this and work for me,
ref : https://github.com/go-playground/validator/issues/617
type Auth struct {
APIKey string `json:"apiKey" validate:"required_without=Username,required_without=Password"`
Username string `json:"username" validate:"required_without=APIKey"`
Password string `json:"password" validate:"required_without=APIKey"`}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论