Golang Validator with custom structs

Viewed 8571

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
}
3 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"`
    ...
}

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

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

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.

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. 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.

Example:

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