GoLang验证器非必填字段返回错误

huangapple go评论67阅读模式
英文:

GoLang Validator Non-Required Fields Returns Error

问题

我正在使用GoLang Validator来验证结构体的字段。尽管我没有添加required标签,但它仍然表现得像是必需的。

type Order struct {
    // ... 其他字段
    UserID string `json:"userId" validate:"uuid4"`
    // ... 其他字段
}

if err = validator.New().Struct(i); err != nil {
    return err
}

输出:User ID: 未知错误

尽管它不是必需的,但它仍然返回错误。我在这里做错了什么吗?

英文:

I'm using GoLang Validator on a struct to validate its fields. Even though I don't add required tag, it still behaves as if it is required.

type Order struct {
    // ... other fields
    UserID string `json:"userId" validate:"uuid4"`
    // ... other fields
}

if err = validator.New().Struct(i); err != nil {
    return err
}

Output: User ID: unknown error

It is not required hence the value is zero-value but it still returns an error. Am I doing something wrong here?

答案1

得分: 1

你应该在字段上添加omitempty验证器以允许空值。在Go Playground上尝试下面的代码。

	type Order struct {
		// ... 其他字段
		UserID string `json:"omitempty,userId" validate:"omitempty,uuid4"`
		// ... 其他字段
	}

	if err := validator.New().Struct(Order{}); err != nil {
		return err
	}

请注意,如果你想允许空值,还需要设置omitempty验证器来将结构体编组为JSON。

英文:

You should add the omitempty validator to allow empty values. Try out the code below on Go playground.

	type Order struct {
		// ... other fields
		UserID string `json:"omitempty,userId" validate:"omitempty,uuid4"`
		// ... other fields
	}

	if err := validator.New().Struct(Order{}); err != nil {
		return err
	}

Note that to marshal the struct to JSON you also need to set the omitempty validator if you want to allow empty values...

huangapple
  • 本文由 发表于 2022年6月21日 20:42:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/72700980.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定