如何使用gopkg.in/go-playground/validator.v9验证字符串切片
Solution for String Slice Validation with validator.v9
Hey there! Let's get your string slice validation sorted with the gopkg.in/go-playground/validator.v9 package. Here's a complete implementation that covers all 5 of your requirements, plus clear explanations for each part:
Full Working Code
package main import ( "fmt" "gopkg.in/go-playground/validator.v9" ) var validate *validator.Validate func main() { validate = validator.New() validateVariable() // Optional: Test invalid cases to see error messages testInvalidCases() } func validateVariable() { // Valid example slice mySlice := []string{"111", "222", "shortstring"} errs := validate.Var(mySlice, "required,slice,max=10,dive,string,max=12") if errs != nil { fmt.Println("Validation errors for valid slice:") for _, err := range errs.(validator.ValidationErrors) { fmt.Printf("- Field: %s, Tag: %s, Value: %v\n", err.Field(), err.Tag(), err.Value()) } } else { fmt.Println("Valid slice passed all checks!") } } func testInvalidCases() { fmt.Println("\n--- Testing Invalid Cases ---") // Case 1: Empty slice emptySlice := []string{} errs := validate.Var(emptySlice, "required,slice,max=10,dive,string,max=12") if errs != nil { fmt.Println("Empty slice errors:") for _, err := range errs.(validator.ValidationErrors) { fmt.Printf("- %s\n", err.Error()) } } // Case 2: Slice longer than 10 elements longSlice := make([]string, 11) for i := 0; i < 11; i++ { longSlice[i] = "test" } errs = validate.Var(longSlice, "required,slice,max=10,dive,string,max=12") if errs != nil { fmt.Println("\nLong slice errors:") for _, err := range errs.(validator.ValidationErrors) { fmt.Printf("- %s\n", err.Error()) } } // Case 3: Element longer than 12 characters invalidElementSlice := []string{"111", "thisstringistoolong123"} errs = validate.Var(invalidElementSlice, "required,slice,max=10,dive,string,max=12") if errs != nil { fmt.Println("\nInvalid element length errors:") for _, err := range errs.(validator.ValidationErrors) { fmt.Printf("- %s\n", err.Error()) } } }
Breakdown of Validation Tags
Each tag maps directly to your requirements:
required: Ensures the slice is not nil and has a length greater than 0 (covers requirement 3)slice: Forces the value to be a slice type (covers requirement 1)max=10: Limits the slice's maximum length to 10 (covers requirement 2)dive: Tells the validator to inspect each individual element of the slicestring: Ensures each element is a string type (covers requirement 4; while Go's type system enforces this for[]string, it adds robustness if you ever useinterface{})max=12: Restricts each string element to a maximum length of 12 characters (covers requirement 5)
Key Notes
- The
divetag is critical here—it lets the validator apply rules to slice elements instead of just the slice itself. - When handling errors, casting
errstovalidator.ValidationErrorsgives you detailed context (like which tag failed and the problematic value).
内容的提问来源于stack exchange,提问作者elham anari
相关产品推荐
相关产品推荐

