简体   繁体   English

带有自定义结构的 Golang 验证器

[英]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
}

From the example here , you can do something like below:这里的示例中,您可以执行以下操作:

type Rule struct {
    ...
}
type Item struct {
    ...
    Rules []Rule `json:"rules" db:"rules" validate:"required"`
    ...
}

There are two ways to do it有两种方法可以做到

  1. Greater Than : For numbers, this will ensure that the value is greater than the parameter given.大于:对于数字,这将确保该值大于给定的参数。 For strings, it checks that the string length is greater than that number of characters.对于字符串,它检查字符串长度是否大于该字符数。 For slices, arrays and maps it validates the number of items.对于切片,arrays 和映射它验证项目的数量。

Example:例子:

Rules       []Rule    `json:"rules" db:"rules" validate:"gt=2"` 
  1. Minimum : For numbers, min will ensure that the value is greater or equal to the parameter given.最小值:对于数字,min 将确保该值大于或等于给定的参数。 For strings, it checks that the string length is at least that number of characters.对于字符串,它会检查字符串长度是否至少为该字符数。 For slices, arrays, and maps, validates the number of items.对于切片,arrays 和映射,验证项目数。

Example:例子:

Rules       []Rule    `json:"rules" db:"rules" validate:"min=3"`

You can use dive to tell the validator to dive into a slice:您可以使用dive告诉验证器深入到一个切片中:

Rules       []Rule    `json:"rules" db:"rules" validate:"dive"`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM