4

I have this struct

// CreateAccount Create Account Data Args
type CreateAccount struct {
    ....
    RegistrationID string  `example:"2c45e4ec-26e0-4043-86e4-c15b9cf985a2" json:"registration_id" binding:"max=63"`
    ParentID       *string `example:"7c45e4ec-26e0-4043-86e4-c15b9cf985a7" json:"parent_id" format:"uuid"`
}

ParentID is a pointer, and it is optional. But if it is provided, it should be uuid.

var params helper.CreateAccount
if err := ctx.ShouldBindJSON(&params); err != nil {
...
}

if add this to ParentID binding:"uuid", it makes ParentID a required filed! Which is not the case here. If and only if ParentID is given, it should be uuid. Is there anyway to set it up this way.

Dan
  • 681
  • 2
  • 11
  • 23
  • have you tried using omitempty? – Pocket Mar 02 '21 at 02:10
  • Yea, if i use it like this `json:"parent_id,omitempty"`, there is no uuid validation for ParentID. And if I add it like this `json:"parent_id,omitempty" binding:"uuid"`, it does the uuid validation. But, it makes ParentID a required filed. – Dan Mar 02 '21 at 04:30

1 Answers1

5

You have to place the omitempty tag first.

type CreateAccount struct {
    ....
    RegistrationID string  `json:"registration_id" binding:"max=63"`
    ParentID       *string `json:"parent_id" binding:"omitempty,uuid"`
}

From the validator docs:

Allows conditional validation, for example if a field is not set with a value (Determined by the "required" validator) then other validation such as min or max won't run

The way I read this sentence is that omitempty has to be placed before others, so that it can stop the validator chain if the value is not equal to the zero value.

blackgreen
  • 34,072
  • 23
  • 111
  • 129