登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-03-29 20:00:33 449浏览 收藏

哈喽!大家好,很高兴又见面了,我是golang学习网的一名作者,今天由我给大家带来一篇《如何在 Go Validator 中只接受多个字段之一?》,本文主要会讲到等等知识点,希望大家一起学习进步,也欢迎大家关注、点赞、收藏、转发! 下面就一起来看看吧!

问题内容

type CoolName struct {
    Foo string  `json:"foo"`
    Bar string  `json:"bar"`
}

使用 go 验证器,我只想将这两个字段之一设为必填,并在如果两个字段的内容都已满时给出错误。

我使用了 required_without 但它只有助于需要其中之一。我不知道如何验证两个字段是否同时没有内容。


正确答案


我刚刚花了一些时间来解决同样的问题,但我似乎已经解决了:

type coolname struct {
    foo string  `json:"foo" validate:"required_without=bar,excluded_with=bar"`
    bar string  `json:"bar" validate:"required_without=foo,excluded_with=foo"`
}

这确实有效,甚至有一定道理。但是,我发现有关 _with/_without 标签的文档有点误导:

仅当任何其他指定字段不存在时,验证字段必须存在且不能为空。

对我来说,这意味着“字段必须存在 <=>(当且仅当)其他字段不存在”。

我已经遵循这一点并为我工作, 参考: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"`}

终于介绍完啦!小伙伴们,这篇关于《如何在 Go Validator 中只接受多个字段之一?》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>