我可以帮你翻译。你想知道是否可以从父结构的值进行条件验证。

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

Can I conditional validate from parent struct value ? (https://github.com/go-playground/validator)

问题

我正在尝试使用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"` // 如果父结构的Enabled为true,则该结构将是必需的
  } `json:"reason" validate:"required"`
}
英文:

I'm trying to validate using https://github.com/go-playground/validator.

I'm facing problem that conditional validation depend on parent struct value.

First of all that validation can be done ?
If can not be, could you give me a hint that solve these problems.

Thanks.

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

答案1

得分: 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"` 
}

另一种方法是自定义验证函数,可以参考这个链接:https://pkg.go.dev/github.com/go-playground/validator/v10#hdr-Custom_Validation_Functions

英文:

Just define Reason as pointer so it will be fine.

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

Another way: u can custom the validate https://pkg.go.dev/github.com/go-playground/validator/v10#hdr-Custom_Validation_Functions

huangapple
  • 本文由 发表于 2022年6月2日 17:43:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/72474095.html
匿名

发表评论

匿名网友

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

确定