Golang:验证字符串类型的结构字段是特定值之一
Golang版本:1.18.3
验证器:github.com/go-playground/validator/v10
我想在加载到嵌套的结构数据结构中后验证传入的JSON有效负载。这是我传入的JSON有效负载,
{
"name": "Duro",
"gender": "MALE",
"tier": 3,
"mobileNumber": "0356874586",
"address": {
"city": "Tokyo",
"street": "Shibaura St"
},
"children":[
{
"title": "Mr",
"lastName": "Takayashi"
}
],
"isEmployed": false,
"requestedAt": "2022-01-10T03:30:12.639Z"
}
这是我的用户。go文件,
package main
type User struct {
Name string `validate:"required"`
Gender string `validate:"required,oneof=MALE FEMALE"`
Tier *uint8 `validate:"required,eq=0|eq=1|eq=2|eq=3"`
MobileNumber string `validate:"required"`
Email string
Address *Address `validate:"required"`
Children []Child `validate:"required,dive"`
IsEmployed *bool `validate:"required"`
PreferredContactMethod string `validate:"oneof=EMAIL PHONE POST SMS"`
RequestedAt time.Time `validate:"required"`
}
type Address struct {
City string `validate:"required"`
Street string `validate:"required"`
}
type Child struct {
Title string `validate:"required"`
FirstName string
LastName string `validate:"required"`
}
这是我的测试功能,
func TestUserPayload(t *testing.T) {
validate := validator.New()
var u User
err := json.Unmarshal([]byte(jsonData), &u)
if err != nil {
panic(err)
}
err := validate.Struct(&u)
if err != nil {
t.Errorf("error %v", err)
}
}
此测试失败而发生了错误,
error Key: 'User.PreferredContactMethod' Error:Field validation for 'PreferredContactMethod' failed on the 'oneof' tag
这发生了,因为GO将空字符串分配给user.preferredcontactmethod结构字段。由于preferredContactMethod
不是必需的字段,因此当JSON有效负载没有它时,我不想看到此验证错误。 当JSON有效载荷没有PreferredContactMethod
字段时,我如何避免此错误消息?
如果您有更好的替代方案来实现此验证,也很乐意听到他们的声音。
golang version: 1.18.3
validator: github.com/go-playground/validator/v10
I want to validate an incoming JSON payload after loaded into nested struct data structure. Here's my incoming JSON payload,
{
"name": "Duro",
"gender": "MALE",
"tier": 3,
"mobileNumber": "0356874586",
"address": {
"city": "Tokyo",
"street": "Shibaura St"
},
"children":[
{
"title": "Mr",
"lastName": "Takayashi"
}
],
"isEmployed": false,
"requestedAt": "2022-01-10T03:30:12.639Z"
}
Here's my user.go file,
package main
type User struct {
Name string `validate:"required"`
Gender string `validate:"required,oneof=MALE FEMALE"`
Tier *uint8 `validate:"required,eq=0|eq=1|eq=2|eq=3"`
MobileNumber string `validate:"required"`
Email string
Address *Address `validate:"required"`
Children []Child `validate:"required,dive"`
IsEmployed *bool `validate:"required"`
PreferredContactMethod string `validate:"oneof=EMAIL PHONE POST SMS"`
RequestedAt time.Time `validate:"required"`
}
type Address struct {
City string `validate:"required"`
Street string `validate:"required"`
}
type Child struct {
Title string `validate:"required"`
FirstName string
LastName string `validate:"required"`
}
Here's my test function
func TestUserPayload(t *testing.T) {
validate := validator.New()
var u User
err := json.Unmarshal([]byte(jsonData), &u)
if err != nil {
panic(err)
}
err := validate.Struct(&u)
if err != nil {
t.Errorf("error %v", err)
}
}
This test fails with error,
error Key: 'User.PreferredContactMethod' Error:Field validation for 'PreferredContactMethod' failed on the 'oneof' tag
This happens because Go assigns empty string to User.PreferredContactMethod struct field. Since PreferredContactMethod
is NOT a required field, I DON'T want to see this validation error when json payload doesn't have it.
How can I avoid this error message when the json payload doesn't have preferredContactMethod
field?
If you have better alternatives to achieve this validation, happy to hear them as well.
Here's the code in Go Playground
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
利用
omitempty
以及Oneof
来使验证器库忽略空或未设置的值。Utilize
omitempty
along withoneof
to make the validator library ignore empty or unset values.使用 https://github.com/marrow16/valix ( https://pkg.go.dev/github.com/marrow16/valix )可以通过以下内容来实现:
go playground: https://go.dev/play/p/3zrkzx97m-e
披露:我是Valix的作者
Using https://github.com/marrow16/valix (https://pkg.go.dev/github.com/marrow16/valix) it could be achieved with the following:
Go playground here: https://go.dev/play/p/3zrkZx97m-e
Disclosure: I am the author of Valix