【问题标题】:Can I conditional validate from parent struct value ? (https://github.com/go-playground/validator)我可以从父结构值有条件地验证吗? (https://github.com/go-playground/validator)
【发布时间】:2022-11-04 12:11:31
【问题描述】:

我正在尝试使用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"` // if parent's Enabled is true that struct will be required 
  } `json:"reason" validate:"required"`
}

【问题讨论】:

    标签: go


    【解决方案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"` 
    } 
    

    【讨论】:

      猜你喜欢
      • 2014-06-24
      • 1970-01-01
      • 1970-01-01
      • 2011-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-27
      • 2013-12-24
      相关资源
      最近更新 更多