Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gin Validation for optional pointer to be uuid?

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.

like image 955
Danial Avatar asked Oct 30 '25 04:10

Danial


1 Answers

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.

like image 61
blackgreen Avatar answered Oct 31 '25 17:10

blackgreen