[英]Golang Validator with custom structs
I am trying to use the Golang Validator ( https://godoc.org/gopkg.in/go-playground/validator.v9 ) to validate a Request body.我正在尝试使用 Golang 验证器( https://godoc.org/gopkg.in/go-playground/validator.v9 )来验证请求正文。 I have two entities, Rule and Item.我有两个实体,规则和项目。 The Item entity relies on the Rule entity. Item 实体依赖于 Rule 实体。
type Rule struct {
RuleNo int64 `json:"ruleNo" db:"rule_no"`
Category string `json:"category" db:"category" validate:"alphanum"`
CreatedAt time.Time `json:"createdAt" db:"created_at"`
UpdatedAt time.Time `json:"updatedAt" db:"updated_at"`
}
type Item struct {
SeqNo int64 `json:"-" db:"item_restriction_no"`
ItemId string `json:"itemId" db:"item_id" validate:"alphanum"`
ItemType string `json:"itemType" db:"item_type" validate:"alphanum"`
Rules []Rule `json:"rules" db:"rules"` // how to validate this field?
CreatedAt time.Time `json:"createdAt" db:"created_at"`
UpdatedAt time.Time `json:"updatedAt" db:"updated_at"`
}
How can I validate that a Request body has a list of Rules for the "Rules" field for the Item struct?如何验证请求正文是否具有 Item 结构的“规则”字段的规则列表? This is my validate function:这是我的验证 function:
func (item *Item) Validate() error {
v := validator.New()
if err := v.Struct(item); err != nil {
return err
}
return nil
}
There are two ways to do it有两种方法可以做到
Example:例子:
Rules []Rule `json:"rules" db:"rules" validate:"gt=2"`
Example:例子:
Rules []Rule `json:"rules" db:"rules" validate:"min=3"`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.