我正在尝试使用 go-playground/validator/v10 包验证 Golang 中的结构字段。具体来说,我想使用 oneof 标签来验证字段值是否与预定义值之一匹配,其中包括带单引号 (') 的字符串。这是我使用的代码:
package main
import (
"fmt"
"github.com/go-playground/validator/v10"
)
// Struct with validation tag
type Award struct {
Title string `validate:"oneof=palm'dor level'dor 'state award'"`
}
func main() {
validate := validator.New()
// Test cases
testCases := []Award{
{"palm'dor"}, // Expected: Valid
{"level'dor"}, // Expected: Valid
{"state award"}, // Expected: Valid
{"other"}, // Expected: Invalid
}
for _, testCase := range testCases {
err := validate.Struct(testCase)
if err != nil {
fmt.Printf("Input: %q - Invalid (%v)\n", testCase.Title, err)
} else {
fmt.Printf("Input: %q - Valid\n", testCase.Title)
}
}
}
预期行为:程序应验证“palm'dor”、“level'dor”和“state award”是否为有效输入。任何其他值都应标记为无效。
问题:当我运行该程序时,我得到以下输出:
Input: "palm'dor" - Invalid (Key: 'Award.Title' Error:Field validation for 'Title' failed on the 'oneof' tag)
Input: "level'dor" - Invalid (Key: 'Award.Title' Error:Field validation for 'Title' failed on the 'oneof' tag)
Input: "state award" - Valid
Input: "other" - Invalid (Key: 'Award.Title' Error:Field validation for 'Title' failed on the 'oneof' tag)