如何在Go Validator中只接受多个字段中的一个?

huangapple go评论77阅读模式
英文:

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"`}

huangapple
  • 本文由 发表于 2022年11月2日 16:03:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/74286009.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定