Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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
}
like image 463
David Pham Avatar asked Oct 31 '25 09:10

David Pham


2 Answers

From the example here, you can do something like below:

type Rule struct {
    ...
}
type Item struct {
    ...
    Rules []Rule `json:"rules" db:"rules" validate:"required"`
    ...
}
like image 85
stevenferrer Avatar answered Nov 03 '25 10:11

stevenferrer


You can use dive to tell the validator to dive into a slice:

Rules       []Rule    `json:"rules" db:"rules" validate:"dive"`
like image 20
Fedor Gorbunov Avatar answered Nov 03 '25 09:11

Fedor Gorbunov