-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathvalidate_max.go
65 lines (58 loc) · 1.36 KB
/
validate_max.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
package changeset
import (
"strconv"
"strings"
)
// ValidateMaxErrorMessage is the default error message for ValidateMax.
var ValidateMaxErrorMessage = "{field} must be less than {max}"
// ValidateMax validates the value of given field is not larger than max.
// Validation can be performed against string, slice and numbers.
func ValidateMax(ch *Changeset, field string, max int, opts ...Option) {
val, exist := ch.changes[field]
if !exist {
return
}
options := Options{
message: ValidateMaxErrorMessage,
}
options.apply(opts)
invalid := false
switch v := val.(type) {
case string:
invalid = len(v) > max
case []interface{}:
invalid = len(v) > max
case []*Changeset:
invalid = len(v) > max
case int:
invalid = v > max
case int8:
invalid = v > int8(max)
case int16:
invalid = v > int16(max)
case int32:
invalid = v > int32(max)
case int64:
invalid = v > int64(max)
case uint:
invalid = v > uint(max)
case uint8:
invalid = v > uint8(max)
case uint16:
invalid = v > uint16(max)
case uint32:
invalid = v > uint32(max)
case uint64:
invalid = v > uint64(max)
case uintptr:
invalid = v > uintptr(max)
case float32:
invalid = v > float32(max)
case float64:
invalid = v > float64(max)
}
if invalid {
r := strings.NewReplacer("{field}", field, "{max}", strconv.Itoa(max))
AddError(ch, field, r.Replace(options.message))
}
}