github.com/bytedance/go-tagexpr@v2.7.5-0.20210114074101-de5b8743ad85+incompatible/validator/example_test.go (about) 1 package validator_test 2 3 import ( 4 "fmt" 5 6 vd "github.com/bytedance/go-tagexpr/validator" 7 ) 8 9 func Example() { 10 type InfoRequest struct { 11 Name string `vd:"($!='Alice'||(Age)$==18) && regexp('\\w')"` 12 Age int `vd:"$>0"` 13 Email string `vd:"email($)"` 14 Phone1 string `vd:"phone($)"` 15 Phone2 string `vd:"phone($,'CN')"` 16 *InfoRequest `vd:"?"` 17 Info1 *InfoRequest `vd:"?"` 18 Info2 *InfoRequest `vd:"-"` 19 } 20 info := InfoRequest{ 21 Name: "Alice", 22 Age: 18, 23 Email: "henrylee2cn@gmail.com", 24 Phone1: "+8618812345678", 25 Phone2: "18812345678", 26 } 27 fmt.Println(vd.Validate(info) == nil) 28 29 type A struct { 30 A int `vd:"$<0||$>=100"` 31 Info interface{} 32 } 33 info.Email = "xxx" 34 a := &A{A: 107, Info: info} 35 fmt.Println(vd.Validate(a)) 36 37 type B struct { 38 B string `vd:"len($)>1 && regexp('^\\w*$')"` 39 } 40 b := &B{"abc"} 41 fmt.Println(vd.Validate(b) == nil) 42 43 type C struct { 44 C bool `vd:"@:(S.A)$>0 && !$; msg:'C must be false when S.A>0'"` 45 S *A 46 } 47 c := &C{C: true, S: a} 48 fmt.Println(vd.Validate(c)) 49 50 type D struct { 51 d []string `vd:"@:len($)>0 && $[0]=='D'; msg:sprintf('invalid d: %v',$)"` 52 } 53 d := &D{d: []string{"x", "y"}} 54 fmt.Println(vd.Validate(d)) 55 56 type E struct { 57 e map[string]int `vd:"len($)==$['len']"` 58 } 59 e := &E{map[string]int{"len": 2}} 60 fmt.Println(vd.Validate(e)) 61 62 // Customizes the factory of validation error. 63 vd.SetErrorFactory(func(failPath, msg string) error { 64 return fmt.Errorf(`{"succ":false, "error":"validation failed: %s"}`, failPath) 65 }) 66 67 type F struct { 68 f struct { 69 g int `vd:"$%3==0"` 70 } 71 } 72 f := &F{} 73 f.f.g = 10 74 fmt.Println(vd.Validate(f)) 75 76 fmt.Println(vd.Validate(map[string]*F{"a": f})) 77 fmt.Println(vd.Validate(map[*F]int{f: 1})) 78 fmt.Println(vd.Validate([][1]*F{{f}})) 79 fmt.Println(vd.Validate((*F)(nil))) 80 fmt.Println(vd.Validate(map[string]*F{})) 81 fmt.Println(vd.Validate([]*F{})) 82 83 // Output: 84 // true 85 // email format is incorrect 86 // true 87 // C must be false when S.A>0 88 // invalid d: [x y] 89 // invalid parameter: e 90 // {"succ":false, "error":"validation failed: f.g"} 91 // {"succ":false, "error":"validation failed: {K:a}.f.g"} 92 // {"succ":false, "error":"validation failed: {}.f.g"} 93 // {"succ":false, "error":"validation failed: [0][0].f.g"} 94 // unsupport data: nil 95 // <nil> 96 // <nil> 97 }