首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >是否可以从父结构值中进行条件验证?(https://github.com/go-playground/validator)

是否可以从父结构值中进行条件验证?(https://github.com/go-playground/validator)
EN

Stack Overflow用户
提问于 2022-06-02 09:43:09
回答 1查看 144关注 0票数 0

我正在尝试使用https://github.com/go-playground/validator进行验证。

我面临的问题是,条件验证依赖于父结构值。

首先,验证可以完成吗?如果不能,你能给我一个解决这些问题的提示吗?

谢谢。

代码语言:javascript
复制
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"`
}
EN

回答 1

Stack Overflow用户

发布于 2022-11-04 04:11:31

只需将Reason定义为指针,就可以了。

代码语言:javascript
复制
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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72474095

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档