-
Notifications
You must be signed in to change notification settings - Fork 0
/
validate.go
77 lines (66 loc) · 1.42 KB
/
validate.go
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
72
73
74
75
76
77
package go_validate
import (
"reflect"
"strings"
)
const (
defaultTagName = "validate"
defaultAliasName = "alias"
require = "require"
)
type Validate struct {
tagName string
aliasName string
}
func New() *Validate {
v := &Validate{}
v.tagName = defaultTagName
v.aliasName = defaultAliasName
return v
}
func (v *Validate) SetTagName(tagName string) {
v.tagName = tagName
}
func (v *Validate) SetAliasName(aliasName string) {
v.aliasName = aliasName
}
func (v *Validate) CheckStruct(st interface{}) error {
obj, err := ValidateStruct(st)
if err != nil {
return err
}
return check(obj, v.tagName, v.aliasName)
}
func check(st interface{}, tagName, aliasName string) (err error) {
val := reflect.ValueOf(st)
num := val.NumField()
for i := 0; i < num; i++ {
field := val.Field(i)
fieldType := val.Type().Field(i)
rules := fieldType.Tag.Get(tagName)
if rules == "" || rules == "-" {
return nil
}
title := fieldType.Tag.Get(aliasName)
if title == "" {
title = fieldType.Name
}
for _, v := range strings.Split(rules, ",") {
if v == require {
if CheckValidateRules[v](field) == false {
return GetErrorMessage(title, v)
}
} else {
if CheckValidateRules[require](field) {
if CheckValidateRules[v](field) == false {
return GetErrorMessage(title, v)
}
}
}
}
}
return nil
}
func checkItem(field, title string, rules []string) error {
return nil
}