You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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 slice
  • string: 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 use interface{})
  • max=12: Restricts each string element to a maximum length of 12 characters (covers requirement 5)

Key Notes

  • The dive tag is critical here—it lets the validator apply rules to slice elements instead of just the slice itself.
  • When handling errors, casting errs to validator.ValidationErrors gives you detailed context (like which tag failed and the problematic value).

内容的提问来源于stack exchange,提问作者elham anari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:20:19