-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate.go
More file actions
71 lines (56 loc) · 1.35 KB
/
validate.go
File metadata and controls
71 lines (56 loc) · 1.35 KB
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
64
65
66
67
68
69
70
71
// Copyright 2019 minigo Author. All Rights Reserved.
// License that can be found in the LICENSE file.
package minigo
import (
"reflect"
"fmt"
"regexp"
)
type Validate struct {}
func NewValidate() *Validate {
return new(Validate)
}
func (validate *Validate) Do(ptr interface{}) error {
t := reflect.TypeOf(ptr)
if (t.Kind() != reflect.Ptr) || (t.Elem().Kind() != reflect.Struct) {
panic("struct pointer is required")
}
v := reflect.ValueOf(ptr).Elem()
for i := 0; i < v.NumField(); i++ {
field := v.Type().Field(i)
tag := field.Tag
reg := tag.Get("regexp")
tips := tag.Get("tips")
if reg == "" {
continue
}
v := v.Field(i)
strValue := ""
switch v.Kind() {
case reflect.String:
strValue = v.String()
break
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
strValue = fmt.Sprintf("%d", v.Int())
case reflect.Float32, reflect.Float64:
strValue = fmt.Sprintf("%v", v.Float())
break
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
strValue = string(v.Uint())
break
}
if strValue != "" {
matched, err := regexp.MatchString(reg, strValue)
if err != nil {
panic(err)
}
if !matched {
if tips == "" {
tips = fmt.Sprintf("%s is inlegal", field.Name)
}
return fmt.Errorf(tips)
}
}
}
return nil
}