-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathvalidate.go
51 lines (42 loc) · 1.13 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
package gody
import "github.com/guiferpa/gody/v2/rule"
func DefaultValidate(b interface{}, customRules []Rule) (bool, error) {
return RawDefaultValidate(b, DefaultTagName, customRules)
}
// Validate contains the entrypoint to validation of struct input
func Validate(b interface{}, rules []Rule) (bool, error) {
return RawValidate(b, DefaultTagName, rules)
}
func RawDefaultValidate(b interface{}, tn string, customRules []Rule) (bool, error) {
defaultRules := []Rule{
rule.NotEmpty,
rule.Required,
rule.Enum,
rule.Max,
rule.Min,
rule.MaxBound,
rule.MinBound,
}
return RawValidate(b, tn, append(defaultRules, customRules...))
}
func RawValidate(b interface{}, tn string, rules []Rule) (bool, error) {
fields, err := RawSerialize(tn, b)
if err != nil {
return false, err
}
return ValidateFields(fields, rules)
}
func ValidateFields(fields []Field, rules []Rule) (bool, error) {
for _, field := range fields {
for _, r := range rules {
val, ok := field.Tags[r.Name()]
if !ok {
continue
}
if ok, err := r.Validate(field.Name, field.Value, val); err != nil {
return ok, err
}
}
}
return true, nil
}