I am trying to use the Golang Validator ( https://godoc.org/gopkg.in/go-playground/validator.v9 ) to validate a Request body. I have two entities, Rule and Item. The Item entity relies on the Rule entity.
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? This is my validate 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
Example:
Rules []Rule `json:"rules" db:"rules" validate:"gt=2"`
Example:
Rules []Rule `json:"rules" db:"rules" validate:"min=3"`
You can use dive to tell the validator to dive into a slice:
Rules []Rule `json:"rules" db:"rules" validate:"dive"`
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.