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"`
    ...
}
                        You can use dive to tell the validator to dive into a slice:
Rules       []Rule    `json:"rules" db:"rules" validate:"dive"`
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With