[英]Golang Validator with custom structs
我正在嘗試使用 Golang 驗證器( https://godoc.org/gopkg.in/go-playground/validator.v9 )來驗證請求正文。 我有兩個實體,規則和項目。 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"`
}
如何驗證請求正文是否具有 Item 結構的“規則”字段的規則列表? 這是我的驗證 function:
func (item *Item) Validate() error {
v := validator.New()
if err := v.Struct(item); err != nil {
return err
}
return nil
}
從這里的示例中,您可以執行以下操作:
type Rule struct {
...
}
type Item struct {
...
Rules []Rule `json:"rules" db:"rules" validate:"required"`
...
}
有兩種方法可以做到
例子:
Rules []Rule `json:"rules" db:"rules" validate:"gt=2"`
例子:
Rules []Rule `json:"rules" db:"rules" validate:"min=3"`
您可以使用dive告訴驗證器深入到一個切片中:
Rules []Rule `json:"rules" db:"rules" validate:"dive"`
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.