/
float64_constraint.go
75 lines (71 loc) · 1.75 KB
/
float64_constraint.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
package govalid
import (
"fmt"
"reflect"
)
type float64Constraint struct {
field string
req bool
isMinSet bool
min float64
isMaxSet bool
max float64
customRules []func(string, float64) string
}
func (f64c *float64Constraint) violation(val reflect.Value) string {
var empty bool
f64, ok := val.Interface().(float64)
if !ok && val.FieldByName("Valid").Interface().(bool) {
f64 = val.FieldByName("Float64").Interface().(float64)
empty = false
} else {
empty = f64 == 0
}
if !f64c.req && empty {
return ""
}
if f64c.req && empty {
return fmt.Sprintf("%s is required", f64c.field)
}
if f64c.isMaxSet && f64 > f64c.max {
return fmt.Sprintf("%s can not be greater than %f", f64c.field, f64c.max)
}
if f64c.isMinSet && f64 < f64c.min {
return fmt.Sprintf("%s must be at least %f", f64c.field, f64c.min)
}
for _, f := range f64c.customRules {
if vio := f(f64c.field, f64); vio != "" {
return vio
}
}
return ""
}
func (f64c *float64Constraint) violations(val reflect.Value) []string {
var vs []string
var empty bool
f64, ok := val.Interface().(float64)
if !ok && val.FieldByName("Valid").Interface().(bool) {
f64 = val.FieldByName("Float64").Interface().(float64)
empty = false
} else {
empty = f64 == 0
}
if !f64c.req && empty {
return nil
}
if f64c.req && empty {
vs = append(vs, fmt.Sprintf("%s is required", f64c.field))
}
if f64c.isMaxSet && f64 > f64c.max {
vs = append(vs, fmt.Sprintf("%s can not be greater than %f", f64c.field, f64c.max))
}
if f64c.isMinSet && f64 < f64c.min {
vs = append(vs, fmt.Sprintf("%s must be at least %f", f64c.field, f64c.min))
}
for _, f := range f64c.customRules {
if vio := f(f64c.field, f64); vio != "" {
vs = append(vs, vio)
}
}
return vs
}