1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| package validate
import ( "fmt" )
type User struct { Name string `v:"required,alphaunicode"` Age uint8 `v:"gte=10,lte=130"` Phone string `v:"required,e164"` Email string `v:"required,email"` FavouriteColor string `v:"hexcolor|rgb|rgba|hsl|hsla"` FavouriteColor2 string `v:"iscolor"` Address *Address `v:"required"` ContactUser []*ContactUser `v:"required,gte=1,dive"` Hobby []string `v:"required,gte=2,dive,required,gte=2,alphaunicode"` Data map[string]string `v:"required,gte=2,dive,keys,alpha,len=2,endkeys,required,gte=2,alphaunicode"` }
type ContactUser struct { Name string `v:"required,alphaunicode"` Age uint8 `v:"gte=10,lte=130"` Phone string `v:"required_without_all=Email Address,omitempty,e164"` Email string `v:"required_without_all=Phone Address,omitempty,email"` Address *Address `v:"required_without_all=Phone Email"` }
type Address struct { Province string `v:"required"` City string `v:"required"` }
func StructValidate() { addr := &Address{ Province: "hunan", City: "changsha", } contactUser := &ContactUser{ Name: "nn", Age: 14, Phone: "+8613800138000", } user := &User{ Name: "lin", Age: 11, Phone: "+8613800138000", Email: "lin@xx.cn", FavouriteColor: "#ffff", FavouriteColor2: "rgb(255,255,255)", Address: addr, ContactUser: []*ContactUser{contactUser}, Hobby: []string{"lanqiu", "yumao"}, Data: map[string]string{"AA": "aa", "BB": "bb"}, } err := validate.Struct(user) if err != nil { fmt.Println("valid failed-----") fmt.Println(err) } }
|