github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/zvalid/valid.go (about) 1 // Package zvalid data verification 2 package zvalid 3 4 import ( 5 "container/list" 6 "errors" 7 "strconv" 8 9 "github.com/sohaha/zlsgo/zjson" 10 ) 11 12 type ( 13 // Engine valid engine 14 Engine struct { 15 err error 16 defaultValue interface{} 17 queue *list.List 18 name string 19 value string 20 sep string 21 valueInt int 22 valueFloat float64 23 setRawValue bool 24 silent bool 25 result bool 26 } 27 queueT func(v *Engine) *Engine 28 ) 29 30 var ( 31 // ErrNoValidationValueSet no verification value set 32 ErrNoValidationValueSet = errors.New("未设置验证值") 33 ) 34 35 // New valid 36 func New() Engine { 37 return Engine{ 38 queue: list.New(), 39 } 40 } 41 42 // Int use int new valid 43 func Int(value int, name ...string) Engine { 44 return Text(strconv.FormatInt(int64(value), 10), name...) 45 } 46 47 // Text use int new valid 48 func Text(value string, name ...string) Engine { 49 var obj Engine 50 obj.value = value 51 obj.setRawValue = true 52 obj.queue = list.New() 53 if len(name) > 0 { 54 obj.name = name[0] 55 } 56 return obj 57 } 58 59 func JSON(json *zjson.Res, rules map[string]Engine) (err error) { 60 for k := range rules { 61 v := json.Get(k) 62 rule := rules[k] 63 if v.Exists() { 64 err = rule.VerifiAny(v.Value()).Error() 65 } else { 66 err = rule.Verifi(v.String()).Error() 67 } 68 69 if err != nil { 70 return err 71 } 72 } 73 74 return nil 75 } 76 77 // Required Must have a value (zero values other than "" are allowed). If this rule is not used, when the parameter value is "", data validation does not take effect by default 78 func (v Engine) Required(customError ...string) Engine { 79 return pushQueue(&v, func(v *Engine) *Engine { 80 if v.value == "" { 81 v.err = setError(v, "不能为空", customError...) 82 } 83 return v 84 }) 85 } 86 87 // Customize customize valid 88 func (v Engine) Customize(fn func(rawValue string, err error) (newValue string, newErr error)) Engine { 89 return pushQueue(&v, func(v *Engine) *Engine { 90 v.value, v.err = fn(v.value, v.err) 91 return v 92 }, true) 93 } 94 95 func pushQueue(v *Engine, fn queueT, DisableCheckErr ...bool) Engine { 96 pFn := fn 97 if !(len(DisableCheckErr) > 0 && DisableCheckErr[0]) { 98 pFn = func(v *Engine) *Engine { 99 if v.err != nil { 100 return v 101 } 102 return fn(v) 103 } 104 } 105 queue := list.New() 106 if v.queue != nil { 107 queue.PushBackList(v.queue) 108 } 109 queue.PushBack(pFn) 110 v.queue = queue 111 return *v 112 } 113 114 func ignore(v *Engine) bool { 115 return v.err != nil || v.value == "" 116 } 117 118 func notEmpty(v *Engine) bool { 119 return v.value != "" 120 } 121 122 func setError(v *Engine, msg string, customError ...string) error { 123 if len(customError) > 0 && customError[0] != "" { 124 return errors.New(customError[0]) 125 } 126 if v.name != "" { 127 msg = v.name + msg 128 } 129 130 return errors.New(msg) 131 }