gin
gin copied to clipboard
I'm getting the "Field validation for 'FieldName' failed on the 'required' tag" error, but the field with the required tag is on a referenced table
Description
So I'm testing my edit functionality, when I got the error I mentioned above. IIRC, that feature was already working properly before, but I might have made some changes down the line that broke it. The tables that are relevant to this error has a struct that looks like this:
type ActuatorDeviceInfo struct {
gorm.Model
ID string `gorm:"primarykey; size:40;"`
DeviceName string `json:"device_name"`
TypeId string `gorm:"size:40; index; not null" json:"type_id"`
Type ActuatorType `gorm:"foreignKey:TypeId; constraint:OnUpdate:CASCADE,OnDelete:CASCADE" json:"type"`
Status bool `gorm:"default:false; column:statusz"`
ParentEdgeDeviceId *string `gorm:"size:40; index; not null" json:"parent_edge_device_id" binding:"required"`
ParentEdgeDevice EdgeDeviceInfo `gorm:"foreignKey:ParentEdgeDeviceId; constraint:OnUpdate:CASCADE,OnDelete:CASCADE" json:"parent_edge_device"`
}
type EdgeDeviceInfo struct {
gorm.Model
ID string `gorm:"primarykey; size:40;"`
Name *string `gorm:"not null" binding:"required" json:"name"`
Description string `json:"description"`
Status bool `gorm:"default:false; column:statusz"`
APIKey string `json:"api_key"`
Passcode string `gorm:"default:0000"`
}
The field that is getting mentioned in the error is EdgeDeviceInfo's Name field, and the error is thrown by a call to *gin.Context.ShouldBind()
. Which I call like this:
var actuator_device_info models.ActuatorDeviceInfo
err := ctx.ShouldBind(&actuator_device_info)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{
"error2": err.Error(),
})
return
}
I already saw this issue that's why I also added a pointer and binding:required to ParentEdgeDeviceId, but it didn't work. Why does gin need to check the fields of the referenced table?
Environment
- go version: go version go1.20.4 windows/amd64
- gin version (or commit ref): v1.7.7
- operating system: Windows 10 64bit