如何解决可选指针是否为 uuid 的 Gin 验证?
我有这个结构
// 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 是一个指针,它是可选的。但是如果提供了,应该是uuid。
var params helper.CreateAccount
if err := ctx.ShouldBindJSON(¶ms); err != nil {
...
}
如果将此添加到 ParentID binding:"uuid"
,则使 ParentID 成为必填字段!这不是这里的情况。当且仅当给定了 ParentID,它应该是 uuid。有没有办法这样设置。
解决方法
您必须先放置 omitempty
标签。
type CreateAccount struct {
....
RegistrationID string `json:"registration_id" binding:"max=63"`
ParentID *string `json:"parent_id" binding:"omitempty,uuid"`
}
允许条件验证,例如,如果一个字段没有设置值(由“必需”验证器确定)那么其他验证,例如 min 或 max 将不会运行
我读这句话的方式是omitempty
必须放在其他人之前,这样如果值不等于零值,它就可以停止验证器链。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。